追牛 | |
|
问题描述
一天早晨,农民约翰在清点牛棚里的牛时,发现少了一头牛。他想尽快把牛找回来。约翰在离牛棚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;
}