POJ 3278 Catch That Cow

本文最后更新于:2020年6月10日 下午

【POJ】 3278 Catch That Cow (BFS + 剪枝)

题目链接:poj 3278

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?


Input

Line 1: Two space-separated integers: N and K


Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.


Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.


题目理解

​ 在一个数轴上有一个人FJ,有一头牛Cow,牛始终保持不动,人可以动,移动规则如下

左移或右移一步:耗时1minute

传送至当前坐标的2倍处:耗时1minute

​ 问人找到牛需要的最短时间。

​ 找最短路径,广度优先搜索(BFS) + 剪枝


代码

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int MAXN = 1e5 + 1;

int N, K, next;
queue<int> q;
int vis[MAXN];

int BFS(){
	q.push(N);
	vis[N] = 1; //标记FJ初始位置已被访问 
	while(!q.empty()){
		for(int i = -1; i <= 1; ++i){//尝试用三种方式走
			if(i)
				next = q.front() + i;
			else
				next = q.front() * 2;
			if(next > 0 && next < MAXN && !vis[next]){//这里要注意要后判断vis[next],否则可能数组越界!!!
				q.push(next);
				vis[next] = vis[q.front()] + 1;
			}
			if(next == K)
				return vis[K] - 1;
		}
		q.pop();
	}
} 

int main(){
	while(scanf("%d %d", &N, &K) != EOF){
		memset(vis, 0, sizeof(vis));
		while(!q.empty())
			q.pop();
		if(N >= K)
			printf("%d\n", N - K);
		else
			printf("%d\n", BFS());
	}
	return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!