看上去像是一道质数题,实际上就是BFS。。比较水,不多说直接上代码。
#include <stdio.h>
#include <queue>
#include <string.h>
#define INF 10000000
using namespace std;
int judge[10005],dp[10005];
void solution(){
int i,j;
judge[0]=1;
judge[1]=1;
for(i=2;i<=10000;i++){
if(judge[i]==0)
for(j=i+i;j<=10000;j+=i){
judge[j]=1;
}
}
return;
}
int po(int n){
int e=1;
if(n==0)
return 1;
for(int i=0;i<n;i++)
e*=10;
return e;
}
int main(){
int n,m,i,j,t;
int p,date,charge;
memset(judge,0,sizeof(judge));
solution();
//memset(dp,0,sizeof(dp));
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
queue<int> q;
for(i=1000;i<=10000;i++) dp[i]=INF;
dp[n]=0;
q.push(n);
while(q.size()){
p=q.front(); q.pop();
charge=p;
if(p==m) break;
for(i=1;i<=4;i++){
date=charge%10;
charge=charge/10;
for(j=0;j<10;j++){
int nx=(p-date*po(i-1))+po(i-1)*j;
//printf("nx=%d\n",nx);
if(nx>=1000&&nx<=9999&&judge[nx]==0/*&&nx!=n*/&&dp[nx]==INF){
q.push(nx);
dp[nx]=dp[p]+1;
}
}
}
}
//if(dp[m]<INF)
printf("%d\n",dp[m]);
//else
//printf("no\n");
}
return 0;
}