题目:http://poj.org/problem?id=3126
题意:给两个素数,问你一次只能改变一个数字的话从一个数字到另一个数字需要多少次。
代码:
//MEMORY 648K TIME 16MS
//F判断数字是不是质数jud判断数字有没有被遍历到
//用的BFS
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
bool f[10010],jud[10010];
int p[10010];
int i,j,a,b,temp,m,n;
int k1,k2,k3,k4;//分别是个位十位百位千位
void init()
{
memset(f,true,sizeof(f));
for(i=2; i<=10010; i++)
{
if(f[i])
for(j=2; j*i<10010; j++)
f[i*j]=false;
f[1]=true;
}
}
void bfs(int a,int b)
{
queue<int> q;
q.push(a);
p[a]=0;
jud[a]=false;
while(jud[b])
{ int temp=q.front();
q.pop();
for(int i=0;i<=9;i++)
{ int y1=(temp/10)*10+i;
if(f[y1] && jud[y1])
{ q.push(y1);
p[y1]=p[temp]+1;
jud[y1]=false;
}
int y2=(temp/100)*100+temp%10+i*10;
if(f[y2]&& jud[y2])
{ q.push(y2);
p[y2]=p[temp]+1;
jud[y2]=false;
}
int y3=(temp/1000)*1000+temp%100+i*100;
if(f[y3] && jud[y3])
{ q.push(y3);
p[y3]=p[temp]+1;
jud[y3]=false;
}
if(i!=0)
{ int y4=temp%1000+i*1000;
if(f[y4] && jud[y4])
{ q.push(y4);
p[y4]=p[temp]+1;
jud[y4]=false;
}
}
}
}
}
int main()
{
init();
scanf("%d",&n);
while(n--)
{
memset(jud,true,sizeof(jud));
memset(p,0,sizeof(p));
scanf("%d%d",&a,&b);
bfs(a,b);
int res = p[b];
printf("%d\n",res);
}
}