Virtual Judge - Catch That Cow 题解答案

题目描述
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?

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

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

样例输入
5 17

样例输出
4

提示
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,其中N代表起点,K代表终点,N每次只能+1,-1或者 x 2,问至少需要几步才能得到K。 (0 ≤ N,K ≤ 100,000)

例如输入5 17,那么最少步数为4。走的方法为:(1)5 x 2=10 ,(2)10-1=9,(3)9 x 2 =18,(4)18-1=17

思路很简单,利用BFS遍历起点能到达的点,再由这些点遍历到其他点,当遍历到终点时就得到答案了。

代码

#include<iostream>
using namespace std;
#include<queue>
#include<string>
int n, k; //当前位置,目标位置
bool vis[100005]; //标记数组

struct node
{
	int x, step;  //当前位置,已走步数
};

bool check(int a)	//检测当前位置是否合法
{
	if (a < 0 || a>100000 || vis[a])
		return false;
	return true;
}

int bfs(int x)
{
	node now, next;		
	vis[x] = true;	//当前位置已访问 标记置为真

	now.x = x, now.step = 0;	

	queue<node>q; //创建队列q

	q.push(now);	//将当前位置放入队列

	while (!q.empty())
	{
		now = q.front(); //取队首元素
		q.pop();	//删除队首元素

		if (now.x == k)return now.step;	//判断当前位置是否走到目标位置 走到了就返回走的步数
		
		next.x = now.x + 1; //前进
		if (check(next.x)) //判断走的位置是否合法
		{
			next.step = now.step + 1;	//步数加1
			vis[next.x] = 1;	//当前位置已访问 标记置为真
			q.push(next);		//将该点放入队列
		}

		next.x = now.x - 1; //后退
		if (check(next.x))
		{
			next.step = now.step + 1;
			vis[next.x] = 1;
			q.push(next);
		}

		next.x = now.x*2;	//传送
		if (check(next.x))
		{
			next.step = now.step + 1;
			vis[next.x] = 1;
			q.push(next);
		}
	}
	return -1;
}

int main()
{
	cin >> n >> k;	//输入
	memset(vis,0,sizeof(vis));	//标记数组全部置0

	int res = bfs(n);	//调用bfs
	cout << res << endl;

	//system("pause");
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值