标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1973
Prime Path
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
1 #include <iostream> 2 #include <queue> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 struct node{ 7 int cur, step; 8 }now, Next; 9 int vis[10001], star, finish, prime[10001] = { 0, 0, 1 }; 10 void init(){ 11 for (int i = 2; i < 10001; i++){ 12 if (!prime[i]){ 13 for (int j = 2; i*j < 10001; j++) 14 prime[i*j] = 1; 15 } 16 } 17 } 18 int bfs(){ 19 queue<node> Q; 20 vis[star] = 1; 21 now.cur = star, now.step = 0; 22 Q.push(now); 23 while (!Q.empty()){ 24 int i, j; 25 char num[5]; 26 now = Q.front(); 27 Q.pop(); 28 if (now.cur == finish) return now.step; 29 for (i = 0; i < 4; i++){ 30 sprintf(num, "%d", now.cur); 31 for (j = 0; j < 10; j++){ 32 if (j == 0 && i == 0) 33 continue; 34 if (i == 0) 35 Next.cur = j * 1000 + (num[1] - ‘0‘) * 100 + (num[2] - ‘0‘) * 10 + (num[3] - ‘0‘); 36 else if (i == 1) 37 Next.cur = j * 100 + (num[0] - ‘0‘) * 1000 + (num[2] - ‘0‘) * 10 + (num[3] - ‘0‘); 38 else if (i == 2) 39 Next.cur = j * 10 + (num[0] - ‘0‘) * 1000 + (num[1] - ‘0‘) * 100 + (num[3] - ‘0‘); 40 else if (i == 3) 41 Next.cur = j + (num[0] - ‘0‘) * 1000 + (num[1] - ‘0‘) * 100 + (num[2] - ‘0‘) * 10; 42 if (!prime[Next.cur] && !vis[Next.cur]) 43 { 44 Next.step = now.step + 1; 45 vis[Next.cur] = 1; 46 Q.push(Next); 47 } 48 } 49 } 50 } 51 return -1; 52 } 53 int main(){ 54 int t, ans; 55 cin >> t; 56 init(); 57 while (t--){ 58 cin >> star >> finish; 59 memset(vis, 0, sizeof(vis)); 60 ans = bfs(); 61 if (ans == -1) cout << "Impossible\n"; 62 else cout << ans << endl; 63 } 64 return 0; 65 }
其实这道题学校OJ(Swust OJ)也有但是坑爹的后台数据变成a+b的后台数据了,Orz~~~(无爱了)
[HDU 1973]--Prime Path(BFS,素数表)
标签:
原文地址:http://www.cnblogs.com/zyxStar/p/4580385.html