[kuangbin带你飞]专题一 简单搜索 - F - Prime Path
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 using namespace std; 7 struct node 8 { 9 int x; 10 int s; 11 }; 12 bool prim[10005]; 13 bool vis[10005]; 14 int chr(int x,int i,int j) 15 { 16 int b,s = 1; 17 int tmp = 0; 18 for(int z = 1; z<= 4; z++) 19 { 20 b = x%10; 21 x/=10; 22 if(i==z) b = j; 23 tmp+=s*b; 24 s*=10; 25 } 26 return tmp; 27 } 28 int main() 29 { 30 // freopen("in.in","r",stdin); 31 for(int i = 2; i <= 10000; i++) 32 { 33 if(prim[i]) continue; 34 for(int j = 2; j <= 10000/i; j++) 35 prim[i*j] = true; 36 } 37 queue<node>q; 38 node s, t; 39 int n, a, b, tmp; 40 bool flag; 41 scanf("%d",&n); 42 while(n--) 43 { 44 flag = false; 45 memset(vis,false,sizeof(vis)); 46 scanf("%d%d",&a,&b); 47 s.x = a; 48 s.s = 0; 49 q.push(s); 50 while(q.size()) 51 { 52 s = q.front(); 53 q.pop(); 54 t.s = s.s + 1; 55 vis[s.x] = true; 56 if(s.x == b) 57 { 58 flag = true; 59 break; 60 } 61 for(int i = 1; i <= 4; i++) 62 for(int j = 0; j <= 9; j++) 63 { 64 if(i==4 && j==0) continue; 65 t.x = chr(s.x,i,j); 66 if(prim[t.x] || vis[t.x]) continue; 67 q.push(t); 68 } 69 } 70 while(q.size()) q.pop(); 71 if(flag) cout<<s.s<<endl; 72 else cout<<"Impossible"<<endl; 73 } 74 return 0; 75 }
本文为博主原创文章,未经博主允许不得转载。