poj3278 Catch That Cow

题意:

在同一数轴上,有一头奶牛坐标为k,农夫的坐标为n,要从n运动到k。
有三种方法:
1. 从当前位置x运动到x+1
2. 从当前位置x运动到x-1
3. 当前位置x运动到2*x

思路:

裸裸的BFS不想多解释

直接上代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <algorithm>
#include <queue>
using namespace std;
const int N=100000;
int n,k,ans[N+5];
bool flag[N+5];
queue<int>f;

 int bfs(int n,int k)
{
	f.push(n);  ans[n]=0; flag[n]=1;
	int res,tmp;
	while (!f.empty())
	{
		res=f.front(); f.pop();
		if (res==k) return ans[res];
		for (int i=0; i<=2; i++)
		{
			if (i==0) tmp=res+1;
			else if (i==1) tmp=res-1;
			else tmp=res*2;
			if (tmp<0||tmp>N) continue;
			if (!flag[tmp])
			{
				f.push(tmp);
				flag[tmp]=1; ans[tmp]=ans[res]+1;  
			}
		}
	}
}

 int main()
{
	scanf("%d%d",&n,&k);
	if (n>=k) printf("%d\n",n-k);
	else printf("%d\n",bfs(n,k));
	return 0;
}
posted @ 2019-08-24 16:59  Allen_Gun  阅读(88)  评论(0编辑  收藏  举报