#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
bool prime[10000];
int state[10000];
int pre,obj;
queue<int> record;
void Init(){
for(int i=0;i<10000;i++) prime[i]=true;
for(int i=2;i<10000;i++){
if(prime[i]){
for(int j=2;i*j<10000;j++) prime[i*j]=false;
}
}
}
int BFS(){
if(pre==obj) return 0;
int multi[4]={1,10,100,1000};
int cur;
state[pre]=1;
record.push(pre);
while(!record.empty()){
cur=record.front();
record.pop();
int d[4];
d[0]=(cur/10)*10;
d[1]=(cur/100)*100+cur%10;
d[2]=(cur/1000)*1000+cur%100;
d[3]=cur%1000;
int digit;
for(int a=0;a<4;a++){
for(int b=0;b<=9;b++){
if(a==3&&b==0) continue;
digit=d[a]+multi[a]*b;
if(digit==obj) return state[cur];
if(prime[digit]&&!state[digit]){
record.push(digit);
state[digit]=state[cur]+1;
}
}
}
}
return -1;
}
int main(){
Init();
int ncase;
cin>>ncase;
while(ncase--){
cin>>pre>>obj;
while(!record.empty()) record.pop();
memset(state,0,sizeof(state));
int res;
res=BFS();
if(res==-1) cout<<"Impossible"<<endl;
else cout<<res<<endl;
}
}
Prime Path(POJ 3126)
最新推荐文章于 2021-10-11 16:57:25 发布