Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9519 | Accepted: 5458 |
Description
1033The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.
1733
3733
3739
3779
8779
8179
Input
Output
Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0
题意:给定两个四位数,求从前一个数变到后一个数最少需要几步,改变的原则是每次只能改变某一位上的一个数,而且每次改变得到的必须是一个素数;
思路:将四位数以内的素数筛选出来,bfs时,枚举四位数的每一位上的每一个数;
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5 6 struct node 7 { 8 int num; 9 int step; 10 }; 11 queue<struct node>que; 12 int n,m,flag; 13 bool p[10010],vis[10010]; 14 15 //素数筛; 16 void prime_search() 17 { 18 memset(p,1,sizeof(p)); 19 for(int i = 4; i <= 10000; i+=2) 20 p[i] = 0; 21 for(int i = 3; i <= 100; i++) 22 { 23 if(p[i]) 24 { 25 for(int j = i+i; j <= 10000; j += i) 26 p[j] = 0; 27 } 28 } 29 } 30 31 int bfs() 32 { 33 while(!que.empty()) 34 que.pop(); 35 que.push((struct node){n,0}); 36 vis[n] = 1; 37 int res,tmp,r,t,s; 38 while(!que.empty()) 39 { 40 struct node u = que.front(); 41 que.pop(); 42 if(u.num == m) 43 return u.step; 44 45 //枚举个位数 46 r = u.num%10; 47 for(int k = -9; k <= 9; k++) 48 { 49 t = r+k; 50 if(t >= 0 && t <= 9) 51 { 52 res = (u.num/10)*10+t; 53 if(p[res] && !vis[res]) 54 { 55 que.push((struct node){res,u.step+1}); 56 vis[res] = 1; 57 } 58 } 59 } 60 61 //枚举十位数 62 tmp = u.num/10; 63 r = tmp%10; 64 s = tmp/10; 65 for(int k = -9; k <= 9; k++) 66 { 67 t = r+k; 68 if(t >= 0 && t <= 9) 69 { 70 res = (s*10+t)*10+u.num%10; 71 if(p[res] && !vis[res]) 72 { 73 que.push((struct node){res,u.step+1}); 74 vis[res] = 1; 75 } 76 } 77 } 78 79 //枚举百位数 80 int tmp = u.num/100; 81 r = tmp%10; 82 s = tmp/10; 83 for(int k = -9; k <= 9; k++) 84 { 85 t = r+k; 86 if(t >= 0 && t <= 9) 87 { 88 res = (s*10+t)*100+u.num%100; 89 if(p[res] && !vis[res]) 90 { 91 que.push((struct node){res,u.step+1}); 92 vis[res] = 1; 93 } 94 } 95 } 96 97 //枚举千位数 98 r = u.num/1000; 99 for(int k = -9; k <= 9; k++) 100 { 101 t = r+k; 102 if(t >0 && t <= 9) 103 { 104 res = t*1000+u.num%1000; 105 if(p[res] && !vis[res]) 106 { 107 que.push((struct node){res,u.step+1}); 108 vis[res] = 1; 109 } 110 } 111 } 112 } 113 } 114 int main() 115 { 116 int test; 117 prime_search(); 118 scanf("%d",&test); 119 while(test--) 120 { 121 memset(vis,0,sizeof(vis)); 122 scanf("%d %d",&n,&m); 123 int ans = bfs(); 124 printf("%d\n",ans); 125 } 126 return 0; 127 }