μκ³ λ¦¬μ¦
λ°±μ€_1963_μμ κ²½λ‘
shj718
2022. 7. 2. 21:43
πββοΈ λ¬Έμ
https://www.acmicpc.net/problem/1963
1963λ²: μμ κ²½λ‘
μμλ₯Ό μ λνλ μ’μνλ μ°½μμ΄λ κ²μ μμ΄λ λΉλ°λ²νΈλ₯Ό 4μ리 βμμβλ‘ μ ν΄λμλ€. μ΄λ λ μ°½μμ΄λ μΉν μΉκ΅¬μ λνλ₯Ό λλμλλ°: βμ΄μ μ¬μ¬ λΉλ² λ°κΏ λλ λμμβ βμ μ§κΈ
www.acmicpc.net
𧩠μκ³ λ¦¬μ¦
βοΈλͺ¨λ μ μ λ°©λ¬Έ, μ΅μ νμ ꡬνκΈ° β BFS μκ³ λ¦¬μ¦
μ μ : μ
κ°μ : μ β μ (κ°μ€μΉ = 1)
βοΈμμ ꡬνκΈ°β μλΌν μ€ν λ€μ€μ 체
π‘ μμ΄λμ΄
-ν μ€νΈμΌμ΄μ€λ§λ€ BFS μ§ν.
-μμ νλ³ λ°°μ΄, λ°©λ¬Έ μ¬λΆ λ°°μ΄, νμ μ μ₯ λ°°μ΄μ νμ©.
-μμ ν μλ¦Ώμλ§ λ°κΎΈκΈ° β μλ₯Ό stringμΌλ‘ λ°κΏμ μ§ν. (to_string(), stoi())
π©βπ» μ½λ
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int prime[10000];
bool visited[10000];
int dist[10000];
int change(int num, int pos, int digit) { // ν μ리 μ«μ λ°κΎΈλ ν¨μ
if (pos == 0 && digit == 0) return -1; // λ€ μ리 μκ° μλ κ²½μ° -1 리ν΄
string s = to_string(num);
s[pos] = digit + '0';
return stoi(s);
}
void bfs(int n) { // BFS ν¨μ
queue<int> q;
q.push(n);
visited[n] = true;
dist[n] = 0;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
for (int j = 0; j <= 9; j++) {
int next = change(cur, i, j);
if (next != -1) { // λ€ μ리 μκ° λ§μΌλ©΄
if (prime[next] != 0 && visited[next] == false) {
q.push(next);
visited[next] = true;
dist[next] = dist[cur] + 1;
}
}
}
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// μμ ꡬνκΈ° (μλΌν μ€ν
λ€μ€μ 체)
for (int i = 2; i <= 9999; i++) {
prime[i] = i;
}
for (int i = 2; i <= 9999; i++) {
if (prime[i] == 0) continue;
for (int j = i + i; j <= 9999; j += i) {
prime[j] = 0;
}
}
// input
int t, n, m;
cin >> t;
// ν
μ€νΈμΌμ΄μ€λ§λ€ BFS
for (int i = 0; i < t; i++) {
cin >> n >> m;
// μ΄κΈ°ν
memset(visited, false, sizeof(visited));
memset(dist, 0, sizeof(dist));
// BFS
bfs(n);
// output
if (visited[m] == true) {
cout << dist[m] << '\n';
}
else {
cout << "Impossible" << '\n';
}
}
return 0;
}