很长时间没写了,,因为去考驾照了,现在考完了。
POJ3126是一个BFS的题,DFS实在想不出来是个什么递归。
题意:给出两个素数a and b,问a经历几次变化变为b。
注:每次变化只能变化任意位置的一个数字,每次变化后得到的新数必须为素数。
思路:
4个位置每个位置的数都有十种变化可能性,101010*10-4就是所有可能了。
我们把每一次得到的数进行检验就可以了。
代码:
#include <iostream>
#include <queue>
#include <cmath>
#include <cstring>
#include <string.h>
#include <cstdio>
#include <stdio.h>
using namespace std;
int n,k;
bool prime[10010];
void iprime()
{
int i,j;
for(i=1000;i<=10000;i++)
{
for( j=2;j<i;j++)
{
if(i%j==0)
{
prime[i]=false;
break;
}
}
if(j==i)
{
prime[i]=true;
//cout<<i<<endl;
}
}
}
int BFS()
{
int temp,vtemp,count1[10010],vis[10010],t[4];
queue<int>q;
q.push(n);
memset(count1,0,sizeof(count1));
memset(vis,false,sizeof(vis));
while(!q.empty())
{
temp=q.front();
q.pop();
if(temp==k)
{
return count1[temp];
}
t[0]=temp/1000;
t[1]=temp/100%10;
t[2]=temp/10%10;
t[3]=temp%10;
for(int i=0;i<4;i++)
{
vtemp=t[i];
for(int j=0;j<10;j++)
{
if(j!=vtemp)
{
t[i]=j;
int rtemp=t[0]*1000+t[1]*100+t[2]*10+t[3];
//cout<<rtemp<<endl;
if(!vis[rtemp]&&prime[rtemp])
{
vis[rtemp]=true;
q.push(rtemp);
count1[rtemp]=count1[temp]+1;
}
if(rtemp==k)
{
return count1[rtemp];
}
}
}
t[i]=vtemp;
}
}
return -1;
}
int main()
{
int t;
iprime();
for(cin>>t;t;t--)
{
cin>>n>>k;
int key=BFS();
if(key==-1)
{
cout<<"Impossible"<<endl;
}
else
{
cout<<key<<endl;
}
}
}
注意点:在第一层for循环中的temp值一开始设定为num[i]的值,之后num[i]会被改变,但是我们需要让num[i]在下一次循环时变回初值。
可改良处:
由于会判断很多次素数,我们可以进行素数打表,每次直接比对即可,这样会节省很多时间。
目前BFS在写的过程中我遇到过很多通过路径最后来获取一个值的题目。这个题目我用来统计值的方法显然是用了一个数组,而之前我还用过结构体将节点信息和走到这个节点的time值存储于一个结构体对象中,当然这样建立的queue也是结构体类型的。总之就是有了两种统计方式:1.数组2.结构体。数组第一用写起来其实比结构体要方便,但是如果节点的信息比较多那么还是用结构体更合适。