简单BFS POJ 3126 Prime Path
题目大意就是输入一个T然后输入一个素数,再输入另一个数,输入第一个数变成另一个所需要的最少步数。
代码:
View Code
1 #include <stdio.h> 2 #include <iostream> 3 #include <string.h> 4 5 using namespace std; 6 7 int vis[10005]; 8 int prim[10005],leap; 9 struct node 10 { 11 int n[5],step; 12 int num; 13 }q[4*10005]; 14 void make_prim() 15 { 16 memset(prim,0,sizeof(prim)); 17 int flag = 1,i,j; 18 for(i = 1001;i <= 9999;i += 2) 19 { 20 flag = 1; 21 for(j = 2;j <= i/2;j++) 22 { 23 if(i%j == 0) 24 { 25 flag = 0; 26 break; 27 } 28 } 29 prim[i] = flag; 30 31 } 32 } 33 int num,f,r,target; 34 void get() 35 { 36 int n; 37 n = q[f].num; 38 39 q[f].n[4] = n%10; 40 n /= 10; 41 q[f].n[3] = n%10; 42 n /= 10; 43 q[f].n[2] = n%10; 44 n /= 10; 45 q[f].n[1] = n; 46 } 47 int getsum(struct node temp) 48 { 49 return temp.n[1]*1000+temp.n[2]*100+temp.n[3]*10+temp.n[4]; 50 } 51 void bfs() 52 { 53 int i,j; 54 memset(vis,0,sizeof(vis)); 55 f = r = 0; 56 q[r].num = num; 57 q[r].step = 0; 58 get(); 59 r++; 60 vis[num] = 1; 61 leap = 0; 62 while(f < r) 63 { 64 struct node temp,now; 65 get(); 66 now = q[f]; 67 now.step = q[f].step+1; 68 f++; 69 for(i = 0;i < 10;i++) 70 { 71 for(j = 1;j < 5;j++) 72 { 73 temp = now; 74 if(i != temp.n[j]) 75 { 76 temp.n[j] = i; 77 temp.num = getsum(temp); 78 79 if(!vis[temp.num] && prim[temp.num]) 80 { 81 vis[temp.num] = 1; 82 q[r] = temp; 83 if(temp.num == target) 84 { 85 leap = 1; 86 break; 87 } 88 r++; 89 } 90 } 91 } 92 if(leap) 93 break; 94 } 95 if(leap) 96 break; 97 } 98 return ; 99 } 100 int main() 101 { 102 int t; 103 make_prim(); 104 scanf("%d",&t); 105 106 while(t--) 107 { 108 scanf("%d %d",&num,&target); 109 if(num == target) 110 { 111 puts("0"); 112 continue; 113 } 114 115 bfs(); 116 if(leap) 117 printf("%d\n",q[r].step); 118 else 119 printf("Impossible\n"); 120 121 } 122 123 return 0; 124 }