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 - 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

InputcopyOutputcopy
5 17
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.

首先看到这种题就要想到广度优先搜索,因为这里是要不断的试探哪个能够到达目的地,并且还要判断最短的步数,通过queue就可以很好的判断最短步数,因为在队列中是先进先出,并且在这个题中,每一个试探x-1,x+1,x*2都是同等的一次试探,每一次都是前面一次加1,所以当走了相同的步数有一种情况已经到达了终点了就是最短的步数,因为不可能出现一个y=x-1d的同时还等于x+1还等于x*2是吧,所以当他们三种情况都是在相同的步数下有种情况先到了那就是最少的 步数


#include<iostream>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
#include<set>
#include<queue> 
using namespace std;
int vis[200005];

struct node{
	int x,step;
};
queue<node>q;
int bfs(int x,int y){
	node start,next,now;
	start.x=x,start.step=0;//初始化
	vis[x]=1;
	
	 q.push(start);
	 
	 while(!q.empty()){
	 	 now=q.front();//相当于一个中间变量,保留上一个值 	 
	 	 if(now.x==y){
	 	 	return now.step ;
		  }
		  q.pop(); //先判断是否到达目的地,没有就出站,因为它的值已经被保留了 
		  if(now.x-1>=0&&!vis[now.x-1]){
		  	next.x=now.x-1;
		  	next.step=now.step+1;
		  	vis[now.x-1]=1;
		  	q.push(next);
		  }
		  
		  if(now.x+1<=y&&!vis[now.x+1]){
		  	next.x=now.x+1;
		  	next.step=now.step+1;//这里的now.step与上一个if和下一个if条件中的是一个值,
			  //这就是为了保证这三步都是在一个步骤下,下一步谁先到了谁就是最短的 
		  	vis[now.x+1]=1;
			  q.push(next);
		  }
		  
		  if(now.x<=y&&!vis[now.x*2]){ //这里要注意不能是now.x*2<=y
		  //因为如果这样的话它本身并没有超出范围,但是会少走这里一步 
		  	next.x=now.x*2;
		  	next.step=now.step+1;
		  	vis[now.x*2]=1;
		  	q.push(next);
		  }
	 }
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int n,m;
	
	cin>>n>>m;
	cout<<bfs(n,m)<<endl;

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

H-rosy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值