HyeLog
λ°±μ€_1963_μμ κ²½λ‘ λ³Έλ¬Έ
πβοΈ λ¬Έμ
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;
}
'μκ³ λ¦¬μ¦' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
λ°±μ€_14395_4μ°μ° (0) | 2022.07.02 |
---|---|
λ°±μ€_10026_μ λ‘μμ½ (0) | 2022.07.02 |
λ°±μ€_12886_λκ·Έλ£Ή (0) | 2022.06.24 |
λ°±μ€_14502_μ°κ΅¬μ (0) | 2022.06.16 |
λ°±μ€_16948_λ°μ€ λμ΄νΈ (0) | 2022.06.16 |