描述
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0≤N≤100000),牛位于点K(0≤K≤100000)。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
输入描述
两个整数,N和K。
输出描述
一个整数,农夫抓到牛所要花费的最小分钟数。
用例输入 1
5 17
用例输出 1
4
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=1e5+10;
int n,k;
bool f[N];
struct node{
int x;
int cnt;
};
queue<node> q;
int main(){
cin>>n>>k;
if(n==k){
cout<<0;
return 0;
}
q.push(node{n,0});
while(!q.empty()){
node t=q.front();
int a,b,c;
a=t.x-1;
b=t.x+1;
c=t.x*2;
if(a==k||b==k||c==k){
cout<<t.cnt+1;
return 0;
}
if(a>=0 && !f[a]){
q.push(node{a,t.cnt+1});
f[a]=1;
}
if(b<=100000 && !f[b]){
q.push(node{b,t.cnt+1});
f[b]=1;
}
if(c<=100000 && !f[c]){
q.push(node{c,t.cnt+1});
f[c]=1;
}
q.pop();
}
return 0;
}