Prime Path
POJ - 3126
1 #include<iostream>
2 #include<cstdio>
3 #include<algorithm>
4 #include<cstring>
5 #include<queue>
6 using namespace std;
7
8 int n,m;
9 bool book[100005];
10 //bool prime[10005];
11 struct note
12 {
13 int x;
14 int s;
15 }a,b;
16
17 bool prime(int v) //素数筛不会。。所以用了这个。还好数据小
18 {
19 for(int i=2;i*i<=v;i++)
20 {
21 if(v%i==0) return false;
22 }
23 return true;
24 }
25
26 void bfs()
27 {
28 queue<note>q;
29
30 book[n]=1;
31 a.x=n;
32 a.s=0;
33 q.push(a);
34 while(!q.empty())
35 {
36 a=q.front();
37 q.pop();
38
39 if(a.x==m)
40 {
41 cout<<a.s<<endl;
42 return;
43 }
44
45 for(int i=1;i<=9;i+=2)//个
46 {
47 b.x=a.x/10*10+i;
48 b.s=a.s+1; //这一步应不应该放在下面的if里面??
49 if(book[b.x]==0&& prime(b.x))
50 {
51 book[b.x]=1;
52 q.push(b);
53 }
54 }
55 for(int i=0;i<=9;i++)//十
56 {
57 b.x=a.x/100*100+ 10*i + a.x%10;
58 b.s=a.s+1;
59 if(book[b.x]==0&&prime(b.x))
60 {
61 book[b.x]=1;
62 q.push(b);
63 }
64 }
65 for(int i=0;i<=9;i++)//百
66 {
67 b.x=a.x/1000*1000+ 100*i + a.x%100;
68 b.s=a.s+1;
69 if(book[b.x]==0&&prime(b.x))
70 {
71 book[b.x]=1;
72 q.push(b);
73 }
74 }
75 for(int i=1;i<=9;i++)//千
76 {
77 b.x=1000*i+ a.x%1000;
78 b.s=a.s+1;
79 if(book[b.x]==0&&prime(b.x))
80 {
81 book[b.x]=1;
82 q.push(b);
83 }
84 }
85 }
86 cout<<"Impossible"<<endl;
87 return;
88 }
89
90 int main()
91 {
92 /*memset(prime,0,sizeof(prime));
93 for(int i=2;i<=110;i++){ //筛素数
94 if(prime[i]==0)
95 for(int j=i+i;j<10010;j+=i){
96 prime[j]=1;
97 }
98 } */
99
100 int T;
101 cin>>T;
102 while(T--)
103 {
104 memset(book,0,sizeof(book));
105 cin>>n>>m;
106 bfs();
107 }
108 }
附上筛素数方法 https://www.cnblogs.com/grubbyskyer/p/3852421.html