pipioj 1453: 魔術師PIPIⅡ(bfs)

 1 #define bug(x) cout<<#x<<" is "<<x<<endl
 2 #define IO std::ios::sync_with_stdio(0)
 3 #include <bits/stdc++.h>
 4 using namespace  std;
 5 typedef long long ll;
 6 #define mk make_pair
 7 #define pb push_back
 8 const int inf=2147483647;
 9 const int N=1e5+10;
10 int T,len;
11 int vis[N],ok[N];
12 void gao(){
13     for(int i=2;i<=N;i++){
14         if(!vis[i]){
15             for(int j=i*2;j<=N;j+=i){
16                 vis[j]=1;
17             }
18         }
19     }
20 }
21 char s[10],t[10];
22 struct node{
23     char x[6];
24     int step=0;
25     bool operator < (const node &p)const{
26         return step>p.step;
27     }
28 };
29 
30 int tf(char *x){
31     int y=0;
32     for(int i=1;i<=len;i++){
33         y*=10;
34         y+=x[i]-'0';
35     }
36     return y;
37 }
38 
39 
40 
41 int bfs(){
42     for(int i=1000;i<N;i++){
43         ok[i]=0;
44     }
45     priority_queue<node>q;
46     int x=tf(s);
47     int y=tf(t);
48     node now;
49     for(int i=1;i<=len;i++)now.x[i]=s[i];
50     now.step=0;
51     q.push(now);
52     while(!q.empty()){
53         now=q.top();
54         q.pop();
55         int f=0;
56         ok[tf(now.x)]=1;
57         for(int i=1;i<=len;i++){
58             if(now.x[i]!=t[i]){
59                 f=1;
60                 break;
61             }
62         }
63         if(!f)return now.step;
64         for(int i=1;i<=len;i++){
65             for(int j='0';j<='9';j++){
66                 node next=now;
67                 next.step=now.step+1;
68                 next.x[i]=j;
69                 int y=tf(next.x);
70                 //bug(y);
71                 if(!vis[y]&&!ok[y]){
72                     //printf("##%d\n",y);
73                     q.push(next);
74                 }
75             }
76             
77         }
78     }
79     return -1;
80 }
81 int main(){
82     gao();
83     scanf("%d",&T);
84     while(T--){
85         scanf("%s %s",s+1,t+1);
86         len=strlen(s+1);
87         int x=tf(s);
88         int y=tf(t);
89         printf("%d\n",bfs());
90     }
91 }
92 /*
93 100
94 1009 1097
95 1021 1031
96 1009 1097
97 1033 1033
98 1021 1091
99 */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章