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<iostream>
#include<algorithm>
#include<queue>
#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;
}
發佈了69 篇原創文章 · 獲贊 34 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章