Catch That Cow (广度优先搜索)

Catch That Cow

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.

这道题我打算把它加入人间迷惑行为,真的是特别迷,题目其实特别简单,就是普通的广度优先搜索,但奇怪的是有一个根本没有用的a[100001]数组,你定义了他就AC,如果不定义他就是Runtime超时,但其实题目里根本就没有用到,这也算是学习心得了把,嘿嘿嘿。
直接上代码:

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node //用一个struct来记录当前的位置,和当前位置需要的步数
{
	int x;
	int step;
};
int bfs(int n, int k); //广度优先搜索
int a[100001]; //完全没有作用的a数组,但是他可以保证不超时hhh
int b[100001]; //用来确保位置没有走过,如果走过还要走回来,步数一定是额外的,所以用来记录
int main()
{
	int n, k;
	cin >> n >> k;
	b[n] = 1; //确保开始位置已经走过
	cout << bfs(n, k);
	return 0;
}
int bfs(int n, int k)
{
	queue<node>q; //基本,用队列来保存
	node now, next; //定义现在和下一步
	now.x = n; //现在的位置是n(题目输入)
	now.step = 0; //现在的步数还没有走,是0
	q.push(now); //入队
	while (!q.empty()) //当队列不是空的时候进行不断循环
	{
		now = q.front(); //now为队首
		if (now.x == k) //如果当前位置是最后的结束位置,直接得出结果
			return now.step;
		if (now.x > 0 && !b[now.x - 1]) //计算-1的位置
		{
			next.x = now.x - 1;
			next.step = now.step + 1;
			b[next.x] = 1;
			q.push(next);
		}
		if (now.x < k && !b[now.x+1]) //计算+1的位置
		{
			next.x = now.x + 1;
			next.step = now.step + 1;
			b[next.x] = 1;
			q.push(next);
		}
		if (now.x < k && !b[now.x * 2]) //计算*2的位置
		{
			next.x = now.x * 2;
			next.step = now.step + 1;
			b[next.x] = 1;
			q.push(next);
		}
		q.pop(); //当这个位置遍历结束后,将其移出队列,进行下一步操作
	}
}

之前由于总是感觉代码是正确的,所以做了几组测试数据:
起点 终点 步数

1 6 3
2 15 4
3 4 1
19 54 8
16 25 5
4 86 7
65 21 44
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值