题目链接:POJ3126
思路,先打一个素数表,然后BFS的时候,把4位数每一位单独考虑,看看4位数是否为质数,是的话就加入队列。
AC代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int maxn=10005;
bool f[maxn];
bool vis[maxn];
int n,d1,d2,d3,d4,res;
struct node{
int num;
int step;
};
void tb(){//false is prime
memset(f,false,sizeof(f));
f[0]=true;
f[1]=true;
f[2]=false;
for(int i=2;i<maxn;i++){
if(f[i]) continue;
else{
for(int j=i+i;j<maxn;j+=i){
f[j]=true;
}
}
}
}
void getnum(int n){
d1=n%10;
d2=(n%100)/10;
d3=(n%1000)/100;
d4=n/1000;
}
bool bfs(int s,int e){
memset(vis,false,sizeof(vis));
queue<node> q;
node t1,t2,t3;
t1.num=s;
t1.step=0;
q.push(t1);
vis[s]=true;
while(!q.empty()){
t2=q.front();
q.pop();
//printf("%d\n",t2.num);
if(t2.num==e){
res=t2.step;
return true;
}
getnum(t2.num);
//d4
for(int i=1;i<=9;i++){
if(i!=d4){
int tmp=i*1000+d3*100+d2*10+d1;
if(!f[tmp]&&!vis[tmp]){
t3.num=tmp;
t3.step=t2.step+1;
vis[tmp]=true;
q.push(t3);
}
}
}
//d3
for(int i=0;i<=9;i++){
if(i!=d3){
int tmp=d4*1000+i*100+d2*10+d1;
if(!f[tmp]&&!vis[tmp]){
t3.num=tmp;
t3.step=t2.step+1;
vis[tmp]=true;
q.push(t3);
}
}
}
//d2
for(int i=0;i<=9;i++){
if(i!=d2){
int tmp=d4*1000+d3*100+i*10+d1;
if(!f[tmp]&&!vis[tmp]){
t3.num=tmp;
t3.step=t2.step+1;
vis[tmp]=true;
q.push(t3);
}
}
}
//d1
for(int i=0;i<=9;i++){
if(i!=d1){
int tmp=d4*1000+d3*100+d2*10+i;
if(!f[tmp]&&!vis[tmp]){
t3.num=tmp;
t3.step=t2.step+1;
vis[tmp]=true;
q.push(t3);
}
}
}
}
return false;
}
int main(){
tb();
scanf("%d",&n);
for(int i=0;i<n;i++){
int a,b;
scanf("%d%d",&a,&b);
// getnum(a);
// printf("%d%d%d%d\n",d4,d3,d2,d1);
// getnum(b);
// printf("%d%d%d%d\n",d4,d3,d2,d1);
if(bfs(a,b)) printf("%d\n",res);
else printf("Impossible\n");
}
return 0;
}