追牛

 

追牛
时间限制 : 5000 MS   空间限制 : 65536 KB

问题描述

一天早晨,农民约翰在清点牛棚里的牛时,发现少了一头牛。他想尽快把牛找回来。约翰在离牛棚N米的地方通过望远镜发现了那头牛,那头牛正在距离牛棚K米的地方吃草(你可以理解为:牛棚、约翰和牛在一条直线上)。
农民约翰可以通过两种方法去追牛:步行和瞬间移动。如果约翰所在的点离牛棚的距离为X,那么:
*步行:用一分钟,约翰可以走到点X-1或点X+1
*瞬间移动:用一分钟,约翰可以移动到点2*X
牛一直在原地吃草,不会移动。约翰追到牛最少需要多少分钟?
(K小于N的情况是可能的——何某注)

输入格式

一行,空格间隔的两个整数N和K(0<=N,K<=100000)

输出格式

一行,一个整数,即最短时间。

样例输入

5 17

样例输出

4

提示

追上牛最快的方式是5->10->9->18->17

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+1;
int n,k,ans;
bool vis[maxn+1];
struct node{	int x,tot;};
int bfs(){
	memset(vis,0,sizeof(vis));
	node a;
	queue<node> q;
	a.x = n;
	a.tot = 0;
	q.push(a);
	while(!q.empty()){
		a = q.front();
		if(a.x==k)	return a.tot;
		vis[a.x] = 1;
		q.pop();
		node next;
		for(int i=0;i<3;i++){
			if(!i)	next.x = a.x+1;
			else if(i==1)	next.x = a.x*2;
			else	next.x = a.x-1;
			if(next.x>0&&next.x<maxn&&!vis[next.x]) {
				next.tot = a.tot+1;
				q.push(next);
			}
		}
	}
	return 0;
}
int main(){
	scanf("%d%d",&n,&k);
	if(n>=k){
		cout<<n-k<<endl;
		return 0;
	}
	ans=bfs();
	cout<<ans<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值