您的位置:首页 > 其它

HDOJ 2717 Catch That Cow (BFS)

2012-08-16 10:53 441 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2717

题意:从N到K有3中走法:坐标加1、减1、乘2。求从N到K的最短步数。

思路:BFS

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int n,k,cnt[111111];

void bfs()
{
queue <int> q;
q.push(n);
cnt
=0;
while(!q.empty())
{
int now=q.front();
q.pop();
if(k==now)
break;
int next=now+1;
if(!cnt[next])
{
q.push(next);
cnt[next]=cnt[now]+1;
}
next=now-1;
if(next>=0&&!cnt[next])
{
q.push(next);
cnt[next]=cnt[now]+1;
}
next=2*now;
if(next<=100000&&!cnt[next]&&next-k<k-now)
{
q.push(next);
cnt[next]=cnt[now]+1;
}
}
}

int main()
{
while(scanf("%d%d",&n,&k)==2)
{
memset(cnt,0,sizeof(cnt));
if(n>=k)
cnt[k]=n-k;
else
bfs();
printf("%d\n",cnt[k]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: