#include <map>
#include <set>
#include <list>
#include <cmath>
#include<cctype>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define PI 3.1415926535897932626
using namespace std;
int gcd(int a, int b)
{
return a % b == 0 ? b : gcd(b, a % b);
}
int prime[10001];
inline void sievePrime()
{
for(int i=0;i<10001;i++)
prime[i]=1;
prime[0]=0;
prime[1]=0;
int max=sqrt(10001*1.0);
for(int i=2;i<=max;i++)
{
if(prime[i])
for(int j=i+i;j<10001;j=j+i)
{
prime[j]=0;
}
}
}
char des[5];//
int N,M;
int vis[10010];
char res[5];
int Min;
struct node
{
int data;int leap;
}q[10010];
inline int trans(char *str)
{
int x=0;
for (int i=0;i<4;i++)
x=x*10+str[i]-'0';
return x;
}
void bfs()
{
q[0].data=N;q[0].leap=0;
int front=0,rear=1;
vis[N]=1;
node u,s;
while (front<rear)
{
u=q[front];
if (u.data==M)
{
Min=u.leap;
return ;
}
char tmp[5];char res[5];
sprintf(tmp,"%d",u.data);
strcpy(res,tmp);
for (int i=0;i<4;i++)
{
if (i==0)
{
for (int j=1;j<=9;j++)
{
tmp[i]=j+'0';
int t=trans(tmp);
if (!vis[t] && prime[t])
{
s.data=t;
s.leap=u.leap+1;
q[rear++]=s;
vis[t]=1;
}
}
}
else
{
for (int j=0;j<=9;j++)
{
tmp[i]=j+'0';
int t=trans(tmp);
if (!vis[t] && prime[t])
{
s.data=t;
s.leap=u.leap+1;
q[rear++]=s;
vis[t]=1;
}
}
}
strcpy(tmp,res);
}
front++;
}
Min=-1;
}
int main()
{
int T;
sievePrime();
scanf("%d",&T);
while (T--)
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&N,&M);
sprintf(des,"%d",M);
Min=99999;
bfs();
if(Min!=-1)
printf("%d\n",Min);
else printf("Impossible\n");
}
return 0;
}
2014 UESTC Training for Search Algorithm
最新推荐文章于 2022-04-21 02:38:12 发布