1. 程式人生 > 實用技巧 >POJ - 3126 Prime Path (BFS搜尋)

POJ - 3126 Prime Path (BFS搜尋)

題目連結:https://vjudge.net/problem/POJ-3126

從一個素數到另一個素數,每一步只能改變一個數,途徑的數也必須是素數,求最小步數。

AC程式碼:

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #include<stack>
 7 #include<queue>
 8 
 9 using namespace std;
10
typedef long long ll; 11 const int maxn = 2e6 + 5; 12 const int INF = 0x3f3f3f3f; 13 14 bool isPrime[10005]; 15 int vis[10005]; 16 int prime[10005]; 17 18 void Prime(int R) 19 { 20 memset(isPrime, 0, sizeof(isPrime)); 21 memset(prime, 0, sizeof(prime)); 22 for (int i = 2; i <= R; i++) { 23 if
(!isPrime[i]) { 24 prime[++prime[0]] = i; 25 } 26 for (int j = 1; j <= prime[0] && i * prime[j] <= R; j++) { 27 isPrime[i * prime[j]] = 1; 28 if (i % prime[j] == 0) break; 29 } 30 } 31 } 32 33 struct node 34 { 35 int num;
36 int step; 37 }; 38 39 int st, ed; 40 41 int bfs(int st) 42 { 43 queue<node>qe; 44 node start, next; 45 start.num = st; 46 start.step = 0; 47 memset(vis, 0, sizeof(vis)); 48 qe.push(start); 49 while (!qe.empty()) { 50 node temp = qe.front(); 51 qe.pop(); 52 if (temp.num == ed) { 53 return temp.step; 54 } 55 vis[temp.num] = 1; 56 for (int k = 0; k < 4; k++) { 57 int head = 0; 58 int x = (int)pow(10.0, k); 59 head = temp.num - (temp.num / x % 10) * x; 60 for (int i = 0; i <= 9; i++) { 61 if (x == 1000 && i == 0) continue; 62 next.num = head + i * x; 63 if (next.num > 9999) break; 64 if (!isPrime[next.num] && !vis[next.num]) { 65 next.step = temp.step + 1; 66 qe.push(next); 67 vis[next.num] = 1; 68 } 69 } 70 } 71 } 72 return -1; 73 } 74 75 int main() 76 { 77 Prime(10001); 78 int t; 79 cin >> t; 80 while (t--) 81 { 82 cin >> st >> ed; 83 int ans = bfs(st); 84 cout << ans << endl; 85 } 86 return 0; 87 }