【題目描述】
農夫約翰被通知,他的一隻奶牛逃逸了!所以他決定,馬上出發,儘快把那隻奶牛抓回來.
他們都站在數軸上.約翰在N(O≤N≤100000)處,奶牛在K(O≤K≤100000)處.約翰有兩種辦法移動,步行和瞬移:步行每秒種可以讓約翰從x處走到x+l或x-l處;而瞬移則可讓他在1秒內從x處消失,在2x處出現.然而那隻逃逸的奶牛,悲劇地沒有發現自己的處境多麼糟糕,正站在那兒一動不動.
那麼,約翰需要多少時間抓住那隻牛呢?
【輸入格式】
僅有兩個整數N和K
【輸出格式】
最短時間
【樣例輸入】
5 17
【樣例輸出】
4
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=100007;
int d[maxn];
int main(){
memset(d,-1,sizeof(d));
int n,k;
scanf("%d%d",&n,&k);
queue<int> q;
q.push(n);
d[n]=0;
while(!q.empty()){
int u=q.front();
q.pop();
if(u==k){
printf("%d",d[u]);
return 0;
}
if(u*2<=100000)
{
if(d[u*2]<0)
{
d[u*2]=d[u]+1;
q.push(u*2);
}
}
if(u+1<=100000)
{
if(d[u+1]<0)
{
d[u+1]=d[u]+1;
q.push(u+1);
}
}
if(u-1>=0)
{
if(d[u-1]<0)
{
d[u-1]=d[u]+1;
q.push(u-1);
}
}
}
return 0;
}