poj---3126---Prime Path
题目链接:http://poj.org/problem?id=3126
#include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include<vector> #include<queue> #include<algorithm> using namespace std; typedef long long LL; const int maxn=500009; const int INF=0x3f3f3f3f; const int mod=2009; int a, b; int cnt[maxn], vis[maxn]; bool Isprime(int m) { int k=sqrt(m); for(int i=2; i<=k; i++) { if(m%i==0) return false; } return true; } int bfs() { queue<int >Q; cnt[a]=0; vis[a]=1; Q.push(a); while(Q.size()) { int t=Q.front(); Q.pop(); for(int i=0; i<=9; i++) { int t1=t/10*10+i; if(Isprime(t1)&&!vis[t1]) { cnt[t1]=cnt[t]+1; vis[t1]=1; Q.push(t1); } int t2=t/100*100+i*10+t%10; if(Isprime(t2)&&!vis[t2]) { cnt[t2]=cnt[t]+1; vis[t2]=1; Q.push(t2); } int t3=t/1000*1000+i*100+t%100; if(Isprime(t3)&&!vis[t3]) { cnt[t3]=cnt[t]+1; vis[t3]=1; Q.push(t3); } if(i) { int t4=i*1000+t%1000; if(Isprime(t4)&&!vis[t4]) { cnt[t4]=cnt[t]+1; vis[t4]=1; Q.push(t4); } } if(vis[b]) return cnt[b]; } } return 0; } int main() { int T; scanf("%d", &T); while(T--) { memset(cnt, 0, sizeof(cnt)); memset(vis, 0, sizeof(vis)); scanf("%d %d", &a, &b); int ans=bfs(); printf("%d\n", ans); } return 0; }