POJ 3126 Prime Path 素数筛,bfs
题目: http://poj.org/problem?id=3126
困得不行了,没想到敲完一遍直接就A了,16ms,debug环节都没进行。人品啊。
1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 using namespace std; 5 6 bool prime[10000]; 7 int vis[10000]; 8 int s, t; 9 10 void prime_init() 11 { 12 memset(prime, 1, sizeof(prime)); 13 prime[1] = 0; 14 for(int i = 4; i < 10000; i += 2) 15 prime[i] = 0; 16 for(int i = 3; i < 100; i += 2) 17 { 18 if(prime[i]) 19 { 20 for(int j = i*i; j < 10000; j += i+i) 21 prime[j] = 0; 22 } 23 } 24 } 25 26 queue<int>q; 27 void bfs() 28 { 29 while(!q.empty())q.pop(); 30 memset(vis, 0, sizeof(vis)); 31 q.push(s); 32 vis[s] = 1; 33 while(!q.empty()) 34 { 35 int u = q.front(); 36 q.pop(); 37 if(u == t) 38 { 39 printf("%d\n", vis[u]-1); 40 return; 41 } 42 int a = u % 10; 43 int b = u % 100 - a; 44 int c = u % 1000 - a - b; 45 int d = u - u % 1000; 46 for(int i = u-a; i <= u-a+9; i++) 47 { 48 if(prime[i] && !vis[i]) 49 { 50 q.push(i); 51 vis[i] = vis[u] + 1; 52 } 53 } 54 for(int i = u-b; i <= u-b+90; i += 10) 55 { 56 if(prime[i] && !vis[i]) 57 { 58 q.push(i); 59 vis[i] = vis[u] + 1; 60 } 61 } 62 for(int i = u-c; i <= u-c+900; i += 100) 63 { 64 if(prime[i] && !vis[i]) 65 { 66 q.push(i); 67 vis[i] = vis[u] + 1; 68 } 69 } 70 for(int i = u-d+1000; i <= u-b+9000; i += 1000) 71 { 72 if(prime[i] && !vis[i]) 73 { 74 q.push(i); 75 vis[i] = vis[u] + 1; 76 } 77 } 78 } 79 } 80 81 int main() 82 { 83 prime_init(); 84 int n; 85 scanf("%d", &n); 86 while(n--) 87 { 88 scanf("%d %d", &s, &t); 89 bfs(); 90 } 91 return 0; 92 }