#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iterator>
#include <list>
#include <stack>
#include <math.h>
#include <queue>
using namespace std;
/*
T1 poj 3126
*/
int n,m;
int vis[10005];
int step[10005];
bool pri[10005];
void prime()
{
int i,j;
memset(pri,true,sizeof(pri));
for(i=1000;i<=10000;i++)
{
for(j=2;j*j<=i;j++)
if(i%j == 0)
{
pri[i]=false;
break;
}
}
}
void bfs()
{
int tem[4];
int i;
int a,t;
queue<int> q;
while(!q.empty())
q.pop();
q.push(n);
while(!q.empty())
{
a=q.front();
q.pop();
if(a == m)
{
cout<<step[a]<<endl;
return ;
}
tem[0]=a /1000;//千
tem[1]=a %1000/100;//百
tem[2]=a %100/10;//十
tem[3]=a %10;//个
//个位:
for(i=1;i<10;i+=2)//为奇数,
{
if(i!=tem[3] )
{
t = tem[0]*1000+tem[1] *100+tem[2]*10+i;
if(!vis[t] && pri[t])
{
vis[t]=1;
step[t]=step[a]+1;
q.push(t);
}
}
}
//十位:
for(i=0;i<10;i++)
{
if(i!=tem[2] )
{
t = tem[0]*1000+tem[1] *100+i*10+tem[3];
if(!vis[t] && pri[t])
{
vis[t]=1;
step[t]=step[a]+1;
q.push(t);
}
}
}
//百位:
for(i=0;i<10;i++)
{
if(i!=tem[1] )
{
t = tem[0]*1000+i *100+tem[2]*10+tem[3];
if(!vis[t] && pri[t])
{
vis[t]=1;
step[t]=step[a]+1;
q.push(t);
}
}
}
//千位:
for(i=1;i<10;i++)//千位 1开始
{
if(i!=tem[0] )
{
t = i*1000+tem[1] *100+tem[2]*10+tem[3];
if(!vis[t] && pri[t])
{
vis[t]=1;
step[t]=step[a]+1;
q.push(t);
}
}
}
}
cout<<"Impossible"<<endl;
return ;
}
int main()
{
int cas;
prime();
cin>>cas;
while(cas--)
{
cin>>n>>m;
memset(vis,0,sizeof(vis));
memset(step,0,sizeof(step));
bfs();
}
return 0;
}
图论 BFS POJ 3126
最新推荐文章于 2024-08-15 02:32:16 发布