POJ3278 Catch That Cow【BFS】

 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 - 1 or + 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.

解题思路

题目大意:农夫去追一只逃跑的牛,农夫从n点出发,牛在k点。农夫从x点到下一点可以有三种走法:x-1、x+1、x*2。问最少多少时间可以追到牛。

解题思路:可以使用BFS进行搜索。从起点开始算是第0步,每往下一层+1步,然后遍历三种走法。直到走到k点为止。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
#define MAXN 100010
int vis[MAXN] = { 0 };
int n, k;

struct Node {
	int x;
	int step;
};

void BFS(int start)
{
	queue<Node>myque;
	Node p;
	p.x = start;
	p.step = 0;
	vis[p.x] = 1;
	myque.push(p);
	while (!myque.empty())
	{
		Node tmp = myque.front();
		myque.pop();
		if (tmp.x == k)
		{
			printf("%d\n", tmp.step);
			return;
		}
		else
		{
			if (tmp.x - 1 >= 0 && vis[tmp.x-1] == 0)
			{
				Node next = { tmp.x - 1,tmp.step + 1 };
				myque.push(next);
				vis[tmp.x - 1] = 1;
			}
			if (tmp.x + 1 <= MAXN&&vis[tmp.x + 1] == 0)
			{
				Node next = { tmp.x + 1,tmp.step + 1 };
				myque.push(next);
				vis[tmp.x] = 1;
			}
			if (tmp.x * 2 <= MAXN&&vis[tmp.x * 2] == 0)
			{
				Node next = { tmp.x * 2,tmp.step + 1 };
				myque.push(next);
				vis[tmp.x] = 1;
			}
		}
	}
}

int main()
{
	scanf("%d%d", &n, &k);
	BFS(n);
	return 0;
}

 

posted @ 2020-06-18 15:35  Hu_YaYa  阅读(26)  评论(0)    收藏  举报