您的位置:首页 > 其它

poj3278 bfs

2016-10-12 15:06 190 查看

poj3278 bfs

这道题是很经典的bfs题 比较简单 开始想的时候 思路并没有很清晰 就开始敲代码 导致后面速度放慢 出错调试也慢 没有很快做出来 看来bfs还是不是很熟练

#include <iostream>
#include <string.h>
#include <queue>
#include<algorithm>
const int INF = 0x3f3f3f3f;
using namespace std;
int maxn=100000,n,k;
int a[100005];
void bfs(int x)
{
queue<int>qu;
qu.push(x);a[x]=0;
while(!qu.empty())
{
int temp=qu.front();
qu.pop();
if(temp==k)
return ;
int x1=temp-1;
if(x1>=0 && a[x1]==-1)
{
a[x1]=a[temp]+1;
qu.push(x1);
}
x1=temp+1;int x2=temp*2;
if(x1<=maxn && a[x1]==-1)
{
a[x1]=a[temp]+1;
qu.push(x1);
}
if(x2<=maxn && a[x2]==-1)
{
a[x2]=a[temp]+1;
qu.push(x2);
}
}
}
int main()
{
scanf("%d%d",&n,&k);
memset(a,-1,sizeof(a));
bfs(n);
printf("%d",a[k]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: