hdu 2717:Catch That Cow(BFS)

本文介绍了一个基于BFS算法解决的趣味问题:一个农夫如何在最短时间内找到一只静止不动的牛。通过从当前点出发,利用步行和瞬间传送两种方式,遍历所有可能达到的点,最终找到目标位置。文章详细解释了算法实现过程,并提供了完整的C++代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=2717

Problem 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

题意分析:

一个人要找他的牛,当前位置为x,每次可以去的地方有x+1, x-1, x*2,求到达牛的位置需要多少步。

解题思路:

每次对当前位置BFS,下一步可能是x+1, x-1, x*2,已经走过的不用再走,注意数组越界。

#include <stdio.h>
#include <string.h>
#include <queue>
#define N 200020
using namespace std;
bool book[N]; 
struct date{
	int x;
	int temp;
};
int bfs(int s, int t)
{
	int tx;
	memset(book, false, sizeof(book));
	queue<date>q;
	book[s]=true;
	
	q.push(date{s, 0});
	while(!q.empty())
	{
		date u=q.front();
		q.pop();
		if(u.x==t)
			return u.temp;
		tx=u.x+1;
		if(book[tx]==false && tx>=0 && tx<=t+2)
		{
			book[tx]=true;
			q.push({tx, u.temp+1});
		}
		tx=u.x-1;
		if(book[tx]==false && tx>=0 && tx<=t+2)
		{
			book[tx]=true;
			q.push({tx, u.temp+1});
		}
		tx=u.x*2;
		if(book[tx]==false && tx>=0 && tx<=t+2)
		{
			book[tx]=true;
			q.push({tx, u.temp+1});
		}
	}
}
int main()
{
	int n, k;
	while(scanf("%d%d", &n, &k)!=EOF)
	{
		if(n>k)
			printf("%d\n", n-k);
		else
			printf("%d\n", bfs(n, k));	
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张宜强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值