我是靠谱客的博主 冷酷小刺猬,最近开发中收集的这篇文章主要介绍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;
}

最后

以上就是冷酷小刺猬为你收集整理的Catch That Cow(详解)的全部内容,希望文章能够帮你解决Catch That Cow(详解)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(128)

评论列表共有 0 条评论

立即
投稿
返回
顶部