水题
解题思路:
按位枚举,40入口bfs,对于偶数剪枝,利用根号法判定素数,即n若能被[2,根号n]的数整出即不是素数
源码:
#include <iostream>
#include <memory.h>
#include <math.h>
using namespace std;
int a,b;
typedef struct pr
{
int prime;
int depth;
} num;
bool visit[15000];
num queue[15000];
bool judge_prime(int n)
{
if(n==2 || n==3)
return true;
else if(n<=1 || n%2==0)//剪枝是偶数必然不是素数
return false;
else if(n>=3)
{
for(int i=2;i*i<=n;i++)//根号法判素数
{
if(n%i==0)
return false;
}
return true;
}
}
void bfs()
{
int tail=0,head=0;
queue[head].prime = a;
queue[tail++].depth=0;
visit[a]=true;
while(head<tail)//40入口bfs
{
num x = queue[head++];
if(x.prime == b)
{
cout<<x.depth<<endl;
return;
}
int first = x.prime%10;//个位
int second = (x.prime/10)%10;//十位
for(int i=1;i<=9;i+=2)//枚举个位,偶数必然不是
{
int y = (x.prime/10)*10 + i;
if(!visit[y]&&y!=x.prime&&judge_prime(y))
{
visit[y] = true;
queue[tail].prime = y;
queue[tail++].depth = x.depth + 1;
}
}
for(int i=0;i<=9;i++)//枚举十位
{
int y = (x.prime/100)*100 + i*10 + first;
if(!visit[y]&&y!=x.prime&&judge_prime(y))
{
visit[y] = true;
queue[tail].prime = y;
queue[tail++].depth = x.depth + 1;
}
}
for(int i=0;i<=9;i++)//百位
{
int y = (x.prime/1000)*1000 + i*100 +second*10 + first;
if(!visit[y]&&y!=x.prime&&judge_prime(y))
{
visit[y] = true;
queue[tail].prime = y;
queue[tail++].depth = x.depth + 1;
}
}
for(int i=1;i<=9;i++)//千位
{
int y = i*1000 + x.prime%1000;
if(!visit[y]&&y!=x.prime&&judge_prime(y))
{
visit[y] = true;
queue[tail].prime = y;
queue[tail++].depth = x.depth + 1;
}
}
}
cout<<"Impossible"<<endl;
return;
}
int main()
{
int cases;
cin>>cases;
while(cases--)
{
cin>>a>>b;
memset(visit,false,sizeof(visit));
bfs();
}
return 0;
}