-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathppath.cpp
More file actions
68 lines (62 loc) · 1.48 KB
/
ppath.cpp
File metadata and controls
68 lines (62 loc) · 1.48 KB
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
#include <iostream>
#include <string>
#include <queue>
#include <cmath>
using namespace std;
void sieve(bool x[], int limit) {
for (int i = 2; i < limit; i++)
if (x[i] == false)
for (int j = i; i*j < limit; j++)
x[i*j] = true;
}
int string_to_int(string str) {
int res = 0;
for (int i = 0; i < str.length(); i++)
res = res * 10 + (str[i]-'0');
return res;
}
int main() {
// freopen("input.txt", "r", stdin);
// precalculated primes
bool prime[10000] = {false};
bool visited[10000];
prime[0] = true;
prime[1] = true;
sieve(prime, 10000);
int test_cases;
cin >> test_cases;
while (test_cases--) {
memset(visited, 0, sizeof(visited));
string a, b;
cin >> a >> b;
bool flag = false;
//bfs and check each generation's primality by sieve
queue < pair<string, int> > Q;
Q.push(make_pair(a, 0));
visited[string_to_int(a)] = true;
while (!Q.empty()) {
pair <string, int> ele = Q.front();
Q.pop();
// cout << ele.first << " " << ele.second << endl;
if (ele.first == b) {
cout << ele.second << endl;
flag = true;
break;
}
for (int i = 0; i < ele.first.length(); i++) {
for (char c = '0'; c <= '9'; c++) {
if (i == 0 && c == '0')
continue;
string temp = ele.first;
temp[i] = c;
if (!prime[string_to_int(temp)] && !visited[string_to_int(temp)]) {
Q.push(make_pair(temp, ele.second+1));
visited[string_to_int(temp)] = true;
}
}
}
}
if (flag == false) cout << "Impossible" << endl;
}
return 0;
}