POJ 3278 Catch That Cow

POJ 3278 Catch That Cow

题目大意:
在一个一维的坐标下,FJ和Cow各自处于一个坐标点,Cow不动,然后问FJ追上Cow的最少时间

  • FJ可向前走一步,耗时一分钟
  • FJ可向后走一步,耗时一分钟
  • FJ可走到当前坐标的两倍处,耗时一分钟(坐标均为正数)

具体思路:
分两种情况,若FJ在Cow的前方,那么他只能一步一步往后走,耗时N-K
若FJ在Cow后方,则BFS搜索

#include
#include
#include
#define INF 99999999
using namespace std;
int dis[100001];
int n, k;
void init()
{
     
	//初始化为需要无穷秒到达
	for (int i = 0; i <= 100000; i++)
		dis[i] = INF;
	dis[n] = 0;	//初始位置为0s
}
void bfs()
{
     
	queue<int> q;
	q.push(n);
	while (!q.empty())
	{
     
		int t = q.front();
		q.pop();
		int next[3];
		next[0] = t + 1;
		next[1] = t - 1;
		next[2] = t * 2;
		for (int i = 0; i < 3; i++)
		{
     
			if (next[i] >= 0 && next[i] <= 100000)
			{
     
				int d = dis[next[i]];
				if (d > dis[t] + 1) {
     
					dis[next[i]] = dis[t] + 1;
					q.push(next[i]);
				}	
			}
		}
	}
		
}
int main()
{
     
	scanf("%d%d", &n, &k);
	if (n > k) {
     
		printf("%d\n", n - k);
		return 0;
	}
	init();
	bfs();
	printf("%d\n", dis[k]);
	return 0;
}

你可能感兴趣的:(bfs,&,dfs,OJ题解)