题目链接:http://poj.org/problem?id=3126
解题报告:

#include <iostream> #include <queue> #include <stdio.h> #include <string.h> using namespace std; #define MAXV 10000 bool Prime[MAXV]; ///素数表 bool vis[MAXV]; ///素数是否访问 int cnt[MAXV]; ///cnt[i]表示变换到素数i时,变换的次数,答案及cnt[last]; void init() { ///对素数打表 int i,j; for(i=1000; i<=MAXV; i++) { for(j=2; j<i; j++) if(i%j==0) { Prime[i]=false; break; } if(j==i) Prime[i]=true; } } int bfs(int first,int last) { queue <int>q; int vtemp,t[4]; memset(vis,false,sizeof(vis)); memset(cnt,0,sizeof(cnt)); q.push(first); vis[first]=true; while(!q.empty()) { int v=q.front(); q.pop(); t[0]=v/1000; t[1]=v%1000/100; t[2]=v%100/10; t[3]=v%10; for(int j=0; j<4; j++) { int temp=t[j]; for(int i=0; i<10; i++) { if(i!=temp) { t[j]=i; vtemp=t[0]*1000+t[1]*100+t[2]*10+t[3]; if(!vis[vtemp] && Prime[vtemp]) { cnt[vtemp]=cnt[v]+1; vis[vtemp]=true; q.push(vtemp); } if(vtemp==last) return cnt[vtemp]; } t[j]=temp; } } if(v==last) return cnt[v]; } return -1; } int main() { int n,a,b,key; init(); scanf("%d",&n); while(n--) { scanf("%d%d",&a,&b); key=bfs(a,b); if(key!=-1) printf("%d ",key); else printf("Impossible "); } return 0; }