forked from varnitsingh/OJ-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PPATH.cpp
128 lines (103 loc) · 2.19 KB
/
PPATH.cpp
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Problem: Prime Path
// Contest: SPOJ - Classical
// URL: https://www.spoj.com/problems/PPATH/
// Memory Limit: 1536 MB
// Time Limit: 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
#include <bits/stdc++.h>
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define ll long long int
#define vi vector<int>
#define vii vector<int, int>
#define vc vector<char>
#define vl vector<ll>
#define mod 1000000007
#define INF 1000000009
using namespace std;
vi adj[10001];
vi primes;
bool vis[10001];
int length[10001];
bool isValid(int a, int b) {
int cnt = 0;
int dig1, dig2;
while(a != 0) {
dig1 = a%10;
dig2 = b%10;
a = a/10;
b = b/10;
if(dig1 != dig2) {
cnt++;
}
}
if(cnt == 1) return true;
return false;
}
bool isPrime(int n) {
for(int i = 2; i*i <= n; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
void buildGraph() {
for(int i = 1000; i <= 9999; i++) {
if(isPrime(i)) {
primes.PB(i);
}
}
for(int i = 0; i < (int)primes.size(); i++) {
for(int j = i+1; j < (int)primes.size(); j++) {
if(isValid(primes[i], primes[j])) {
adj[primes[i]].PB(primes[j]);
adj[primes[j]].PB(primes[i]);
}
}
}
}
void bfs(int node) {
vis[node] = 1;
length[node] = 0;
queue<int> q;
q.push(node);
int curr;
while(!q.empty()) {
curr = q.front(); q.pop();
for(int child : adj[curr]) {
if(!vis[child]) {
length[child] = length[curr] + 1;
vis[child] = 1;
q.push(child);
}
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
int a, b;
cin >> t;
buildGraph(); // creating graph with connecting all the 4 digit numbers which remain prime after changing one digit
while(t--) {
cin >> a >> b;
for(int i = 1000; i <= 9999; i++) {
length[i] = -1;
vis[i] = 0;
}
bfs(a);
if(length[b] == -1) {
cout << "Impossible\n";
}
else {
cout << length[b] << "\n";
}
}
return 0;
}