给你两个四位的素数a,b。
a可以改变某一位上的数字变成c,但只有当c也是四位的素数时才能进行这种改变。
请你计算a最少经过多少次上述变换才能变成b。
例如:1033 -> 8179
1033
1733
3733
3739
3779
8779
8179
最少变换了6次。
Input
第一行输入整数T,表示样例数。 (T <= 100)
每个样例输入两个四位的素数a,b。(没有前导零)
Output
对于每个样例,输出最少变换次数,如果无法变换成b则输出"Impossible"。
Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0
思路 : 这个题我写的麻烦了,但是我这个思路好理解,单个字符输入;
更改个位十位百位千位 进行搜索
代码很好理解;
看代码就可以;
AC代码
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
#include<string>
#include<stack>
#define ll long long
using namespace std;
int p(int x)
{
if(x<2)
{
return 0;
}
for(int i=2 ; i*i<=x ; i++)
{
if(x%i==0)
{
return 0;
}
}
return 1;
}
int x,y,z,w,e1,e2,e3,e4;
int book[10][10][10][10];
struct Node
{
int x,y,z,w,s;
Node(){}
Node(int xx,int yy,int zz,int ww,int ss) : x(xx) , y(yy) , z(zz) , w(ww) , s(ss) {}
};
int bfs(int x,int y,int z,int w,int s)
{
memset(book,0,sizeof(book));
book[x][y][z][w] = 1 ;
queue<Node> Q;
Q.push(Node(x,y,z,w,s));
while(!Q.empty())
{
Node u = Q.front() ;
Q.pop() ;
if(u.x == e1 && u.y == e2 && u.z == e3 && u.w==e4)
{
// cout<<u.x<<u.y<<u.z<<u.w<<endl;
return u.s ;
}
for(int j = 1 ; j<=9 ; j++) //千位
{
int xx = j ;
int data = xx * 1000 + u.y * 100 + u.z * 10 + u.w ;
if(p(data)==1 && book[xx][u.y][u.z][u.w] == 0)
{
book[xx][u.y][u.z][u.w] = 1 ;
// cout<<xx<<u.y<<u.z<<u.w<<endl;
int ss=u.s+1;
Q.push(Node(xx,u.y,u.z,u.w,ss));
}
}
for(int j = 0 ; j<=9 ; j++) // 百位
{
int yy = j ;
int data = u.x * 1000 + yy * 100 + u.z * 10 + u.w ;
if(p(data)==1 && book[u.x][yy][u.z][u.w] == 0)
{
book[u.x][yy][u.z][u.w] = 1 ;
// cout<<u.x<<yy<<u.z<<u.w<<endl;
int ss=u.s+1;
Q.push(Node(u.x,yy,u.z,u.w,ss));
}
}
for(int j = 0 ; j<=9 ; j++) //十
{
int zz = j ;
int data = u.x * 1000 + u.y * 100 + zz * 10 + u.w ;
if(p(data)==1 && book[u.x][u.y][zz][u.w] == 0)
{
book[u.x][u.y][zz][u.w] = 1 ;
int ss=u.s+1;
// cout<<u.x<<u.y<<zz<<u.w<<endl;
Q.push(Node(u.x,u.y,zz,u.w,ss));
}
}
for(int j = 0 ; j<=9 ; j++) //个
{
int ww = j ;
int data = u.x * 1000 + u.y * 100 + u.z * 10 + ww ;
if(p(data)==1 && book[u.x][u.y][u.z][ww] == 0)
{
book[u.x][u.y][u.z][ww] = 1 ;
int ss=u.s+1;
// cout<<u.x<<u.y<<u.z<<ww<<endl;
Q.push(Node(u.x,u.y,u.z,ww,ss));
}
}
}
return -1;
}
int main()
{
int T;
cin>>T;
while(T--)
{
char a;
cin>>a;
x=a-'0';
cin>>a;
y=a-'0';
cin>>a;
z=a-'0';
cin>>a;
w=a-'0';
getchar();
cin>>a;
e1=a-'0';
cin>>a;
e2=a-'0';
cin>>a;
e3=a-'0';
cin>>a;
e4=a-'0';
int ans = bfs(x,y,z,w,0) ;
if(ans == -1)
{
cout<<"Impossible"<<endl;
}
else
{
cout<<ans<<endl;
}
}
}