반응형
https://www.acmicpc.net/problem/1963
1963번: 소수 경로
소수를 유난히도 좋아하는 창영이는 게임 아이디 비밀번호를 4자리 ‘소수’로 정해놓았다. 어느 날 창영이는 친한 친구와 대화를 나누었는데: “이제 슬슬 비번 바꿀 때도 됐잖아” “응 지금
www.acmicpc.net
[ 문제풀이 ]
1. visited 배열을 만들어 각 네 자릿수의 방문 여부를 저장합니다.
2. 에라토스테네스의 체를 이용하여 네 자릿수 소수들을 check 배열에 모두 저장합니다.
3. bfs를 이용하여 각 자릿수를 1씩 바꾸어주면서 방문 여부를 판별하고, 방문하지 않았다면 소수 여부를 판별하여 소수라면 queue에 넣어줍니다.
4. A 수가 B수로 변환이 가능하다면 cnt를 출력하고, 그렇지 않다면 Impossible을 출력합니다.
[ 소스코드 ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | #include<iostream> #include<queue> using namespace std; int T, A, B; int check[10000]; int visited[10000]; int bfs(int A, int B) { fill(visited, visited + 10000, 0); queue<pair<int, int>> q; q.push({ A,0 }); visited[A] = 1; while (!q.empty()) { const int cur = q.front().first; const int cnt = q.front().second; q.pop(); if (cur == B) { return cnt; } int temp = cur % 1000; for (int i = 1; i <= 9; i++) { int next = temp + i * 1000; if (visited[next] != 1) { visited[next] = 1; if (check[next] == 0) { q.push({ next, cnt + 1 }); } } } temp = cur; for (int i = 1; i <= 9; i++) { temp += 100; if ((temp % 1000) / 100 == 0) temp -= 1000; if (visited[temp] != 1) { visited[temp] = 1; if (check[temp] == 0) { q.push({ temp, cnt + 1 }); } } } temp = cur; for (int i = 1; i <= 9; i++) { temp += 10; if ((temp % 100) / 10 == 0) temp -= 100; if (visited[temp] != 1) { visited[temp] = 1; if (check[temp] == 0) { q.push({ temp, cnt + 1 }); } } } temp = cur; for (int i = 1; i <= 9; i++) { temp += 1; if (temp % 10 == 0) temp -= 10; if (visited[temp] != 1) { visited[temp] = 1; if (check[temp] == 0) { q.push({ temp, cnt + 1 }); } } } } return -1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> T; for (int i = 2; i <= 5000; i++) { for (int j = 2; j <= 5000; j++) { if (i * j < 10000) { check[i * j] = 1; } else break; } } while (T--) { cin >> A >> B; int temp = bfs(A, B); if (temp != -1) { cout << temp << '\n'; } else { cout << "Impossible\n"; } } } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 12869번 - 뮤탈리스크 (C++) (0) | 2023.06.28 |
---|---|
[ 백준 ] 1707번 - 이분 그래프 (C++) (0) | 2023.06.27 |
[ 백준 ] 5052번 - 전화번호 목록 (C++) (0) | 2023.06.25 |
[ 백준 ] 3649번 - 로봇 프로젝트 (C++) (0) | 2023.06.23 |
[ 백준 ] 14940번 - 쉬운 최단거리 (C++) (0) | 2023.06.22 |