码迷,mamicode.com
首页 > 其他好文 > 详细

搜索------prime path

时间:2016-07-19 09:43:42      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

给定两个数a,b,每次只能变动a的其中一个数,变成的数也必须是素数,问最少经过几次可以变成b;

----------------------------------------------------------------------------------------------

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
#define MAXV 11000
bool prime[MAXV];
void init()//判断是否素数
{
int i,j;
for(i=1000; i<=MAXV; i++)
{
for(j=2; j<i; j++)
if(i%j==0)
{
prime[i]=false;
break;
}
if(j==i) prime[i]=true;
}
}
int bfs(int first,int last)
{
bool dis[MAXV];
queue <int>q;
int v,i,j,temp,vtemp,count[MAXV],t[4];
memset(dis,false,sizeof(dis));
memset(count,0,sizeof(count));

q.push(first);
dis[first]=true;

while(!q.empty())
{
v=q.front();
q.pop();

t[0]=v/1000;
t[1]=v%1000/100;
t[2]=v%100/10;
t[3]=v%10;
// printf("%d %d %d %d",t[0],t[1],t[2],t[3]);

for(j=0; j<4; j++)
{
temp=t[j];
for(i=0; i<10; i++)
if(i!=temp)
{
t[j]=i;
vtemp=t[0]*1000+t[1]*100+t[2]*10+t[3];
if(!dis[vtemp] && prime[vtemp])
{
count[vtemp]=count[v]+1;
dis[vtemp]=true;
q.push(vtemp);
}
if(vtemp==last) return count[vtemp];
}
t[j]=temp;
}
if(v==last) return count[v];
}
return -1;
}
int main()
{
int n,a,b,key;
init();
scanf("%d",&n);
while(n--)
{
scanf("%d%d",&a,&b);
key=bfs(a,b);
if(key!=-1) printf("%d\n",key);
else printf("Impossible\n");
}
return 0;
}

搜索------prime path

标签:

原文地址:http://www.cnblogs.com/biu-biu-biu-/p/5683402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!