Catch That Cow

本文介绍了一个基于广度优先搜索(BFS)算法的问题,即如何计算农夫John使用步行和瞬移两种方式捕捉静止不动的逃逸奶牛所需的最短时间。通过详细解释算法实现过程及代码示例,帮助读者理解该问题的解决方法。

算法:BFS

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

代码:

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <queue>
using namespace std;
int a[400005];
struct dot
{
	int x,step;
};
void bfs(int n,int m)
{   memset(a,0,sizeof(a));
	queue<dot>que;
	dot cur,loer;
	cur.x=n;
	cur.step=0;
	a[n]=1;
	que.push(cur);
	while(que.size())
	{
		loer=que.front();
		que.pop(); 
		if(loer.x==m)
		{
			cout<<loer.step<<endl;
			break;
		}
		for(int i=0;i<3;i++)
		{
			if(i==0)
			cur.x=loer.x+1;
			else if(i==1)
			cur.x=loer.x-1;
			else cur.x=loer.x*2;
			if(cur.x>=0&&!a[cur.x]&&cur.x<200005)//一定要加上cur.x<200005 
			{
				cur.step=loer.step+1;
				a[cur.x]=1;
				que.push(cur);
			}
		}
	}
}
int main()
{
	int n,m,i,j,k;
	while(cin>>n>>m)
		bfs(n,m);
	return 0;
}


转载于:https://www.cnblogs.com/wangyumin/p/5323444.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值