POJ3126 Prime Path(BFS)
题目链接。
AC代码如下:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <queue> #include <algorithm> #include <map> #include <ctype.h> using namespace std; const int maxn = 10000; struct node { int x, s; }; int end; bool vis[maxn], prime[maxn]; int BFS(int s) { if(s == end) return 0; queue<node> Q; memset(vis, 0, sizeof(vis)); vis[s] = true; Q.push((node){s, 0}); while(!Q.empty()) { node e = Q.front(); Q.pop(); for(int i=1; i<=1000; i *= 10) { for(int j=0; j<10; j++) { if(i == 1000 && j == 0) continue; int t = e.x%i+j*i+e.x/(i*10)*(i*10); if(t == end) return e.s+1; if(prime[t]) { if(vis[t]) continue; vis[t] = true; Q.push((node){t, e.s+1}); } } } } return -1; } int main() { int T, s; scanf("%d", &T); memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for(int i=2; i*i<maxn; i++) { if(prime[i]) for(int j=i*i; j<maxn; j += i) { prime[j] = false; } } while(T--) { scanf("%d%d", &s, &end); printf("%d\n", BFS(s)); } return 0; }