注意结构体队列的使用,在队列中,一条完整的路径才是正确的,中间的歧路最后还是走不通
转载:http://blog.csdn.net/yulanarti/article/details/1787971 ——> 说明sprintf()的作用
注意 sprintf(num, "%d", cur.num);//将数字转化为字符串,可以替代 itoa
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cmath> 6 #include <queue> 7 #define sc(x,y) scanf("%d %d",&(x),&(y)) 8 #define pf(x) printf("%d\n", x) 9 #define CL(x, y) memset(x,y,sizeof(x)) 10 using namespace std; 11 const int MAX = 100000; 12 int prime[MAX] = {0}; //素数表 13 int N, a, b, i, j, temp; 14 int used[MAX]; 15 void InitPrime(); 16 void BFS(int x, int y); 17 struct node 18 { 19 int num; 20 int step; 21 }; 22 queue <node> Q; 23 int main() 24 { 25 InitPrime(); 26 cin >> N; 27 while(N--) 28 { 29 cin >> a >> b; 30 CL(used, 0); 31 BFS(a, b); 32 } 33 return 0; 34 } 35 void BFS(int front, int rear) 36 { 37 while(!Q.empty()) 38 Q.pop();//Q.clear();清空 39 node first, cur, next; 40 first.num = front; 41 first.step = 0; 42 used[front] = 1; 43 Q.push(first); 44 while(!Q.empty()) 45 { 46 cur = Q.front(); 47 Q.pop(); 48 if(cur.num == rear) 49 { 50 cout << cur.step << endl; 51 return ; 52 } 53 for(i = 0; i < 4; i++) 54 { 55 char num[5]; 56 sprintf(num, "%d", cur.num);//将数字转化为字符串,可以替代 itoa 57 for (j = 0; j < 10; j++) 58 { 59 if (j == 0 && i == 0)//千位不能为 0 60 continue; 61 if(i == 0) 62 temp = j*1000+(num[1]-‘0‘)*100+(num[2]-‘0‘)*10+(num[3]-‘0‘);//千位 63 else if(i == 1) 64 temp = j*100+(num[0]-‘0‘)*1000+(num[2]-‘0‘)*10+(num[3]-‘0‘);//百位 65 else if(i == 2) 66 temp = j*10+(num[0]-‘0‘)*1000+(num[1]-‘0‘)*100+(num[3]-‘0‘);//十位 67 else if(i == 3) 68 temp = j+(num[0]-‘0‘)*1000+(num[1]-‘0‘)*100+(num[2]-‘0‘)*10;//个位 69 if(prime[temp] && !used[temp]) 70 { 71 next.num = temp; 72 next.step = cur.step+1; 73 used[temp] = 1; 74 // cout << next.num << " " << next.step << endl; 75 Q.push(next); 76 Q.push(next); 77 } 78 } 79 } 80 } 81 printf("Impossible\n"); 82 return ; 83 } 84 void InitPrime() 85 { 86 int i, j; 87 for(i = 1009; i <= 9973; i++) 88 { 89 if(!(i&1))continue; //奇偶判断 90 for(j = 3; j*j <= i; j += 2) 91 { 92 if(0 == i%j) 93 { 94 break; 95 } 96 } 97 if(j * j > i) 98 { 99 prime[i] = 1; 100 } 101 } 102 }
时间: 2024-10-06 00:42:51