문제
https://www.acmicpc.net/problem/17394
설명
- 문제를 전체적으로 풀면 간단하고 명시적으로 소수-> 에라체사용
- 그리고 1, 2, 3, 4번의 경우의 가짓수 -> q의 상태
- 조건에 맞는 소수면 출력 끝!
그러나 아주 큰 실수를했다- > 바보였다....
Eras() 함수에서 Prime[j] = 0;를 해야하는데 Prime[i] = 0으로 했다 아주 바보였다. ㅠㅠㅠㅠ
정답 소스
#include <bits/stdc++.h>
using namespace std;
int n, t, a, b, nx;
//소수의 범위는 2이상 10만이하
int Prime[110000];
bool visited[1000001];
void init() {
for (int i = 1; i <= 100000; i++) Prime[i] = 1;
}
//prime[i] = 1이면 소수이다
void Eras() {
for (int i = 2; i <= 100000; i ++) {
if (Prime[i] == 0) continue;
for (int j = i + i; j <= 100000; j += i) {
Prime[j] = 0;
}
}
}
int bfs() {
queue<pair<int, int>> q;
q.push({ n, 0 });
memset(visited, 0, sizeof(visited));
visited[n] = 1;
while (!q.empty())
{
int now = q.front().first;
int cnt = q.front().second;
q.pop();
//cout << now << " " << cnt << endl;
if (now >= a && now <= b) {
if (Prime[now] == 1) {
return cnt;
}
}
nx = now / 2;
if (!visited[nx]) {
q.push({ nx, cnt + 1 });
visited[nx] = 1;
}
nx = now / 3;
if (!visited[nx]) {
q.push({ nx, cnt + 1 });
visited[nx] = 1;
}
nx = now + 1;
if (!visited[nx]) {
q.push({ nx, cnt + 1 });
visited[nx] = 1;
}
if (now > 2) {
nx = now - 1;
if (!visited[nx]) {
q.push({ nx, cnt + 1 });
visited[nx] = 1;
}
}
}
return -1;
}
int main() {
cin >> t;
init();
Eras();
while (t--)
{
cin >> n >> a >> b;
cout << bfs() << endl;
}
return 0;
}
'알고리즘' 카테고리의 다른 글
K번째 수 백준 1300 (0) | 2021.12.03 |
---|---|
백준 달나라 토끼를 위한 구매대금 지불 도우미 17212번 (0) | 2021.12.03 |
백준 온풍기 안녕! 23289 (0) | 2021.12.02 |
조합 문제. 중복조합 (0) | 2021.11.29 |
백준 가장 긴 바이토닉 부분 수열 11054번 (0) | 2021.11.25 |