HDOJ 2717 Catch That Cow (BFS)

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[n]=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;
}


你可能感兴趣的:(HDOJ 2717 Catch That Cow (BFS))