Description
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 X - 1 or X + 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
Output
Sample Input
5 17
Sample Output
4
Hint
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
struct node
{
int x,step; //x为农夫的坐标,step为农夫走的步数
};
int n,k;
const int N=200005;
queue<node> q;
int vis[N]; //vis为标记数组,记录农夫是否走过这个点
void bfs()
{
int x1,ste;
while(!q.empty())
{
node temp=q.front();
q.pop();
x1=temp.x;
ste=temp.step;
if(x1==k)
{
printf("%d\n",temp.step);
return ;
}
if(x1-1>=0&&!vis[x1-1]) //要保证x1-1有意义
{
node tt;
tt.step=temp.step+1;
tt.x=temp.x-1;
vis[x1-1]=1;
q.push(tt);
}
if(x1<k&&!vis[x1+1])
{
node tt;
tt.step=temp.step+1;
tt.x=temp.x+1;
vis[x1+1]=1;
q.push(tt);
}
if(x1<k&&!vis[2*x1])
{
node tt;
tt.step=temp.step+1;
tt.x=temp.x*2;
vis[x1*2]=1;
q.push(tt);
}
}
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
while(!q.empty()) //每次把队列置空
q.pop();
memset(vis,0,sizeof(vis));
node t;
t.x=n;
t.step=0;
vis[n]=1;
q.push(t);
bfs();
}
return 0;
}