Catch That Cow
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<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#define MAX 200030
using namespace std;
typedef struct node
{
int x,step;
}Node;
int n,k;
int vis[MAX+5];
Node que[MAX+5];
void bfs()
{
int front=0,rear=0;
que[rear].x=n;
que[rear++].step=0;
vis[n]=1;
while(front<rear)
{
Node tmp=que[front++];
if(tmp.x==k)
{
printf("%d\n",tmp.step);
return;
}
if(tmp.x-1>=0&&!vis[tmp.x-1])
{
vis[tmp.x-1]=1;
que[rear].x=tmp.x-1;
que[rear++].step=tmp.step+1;
}
if(tmp.x<=k&&!vis[tmp.x+1])
{
vis[tmp.x+1]=1;
que[rear].x=tmp.x+1;
que[rear++].step=tmp.step+1;
}
if(tmp.x<=k&&!vis[2*tmp.x])
{
vis[2*tmp.x]=1;
que[rear].x=2*tmp.x;
que[rear++].step=tmp.step+1;
}
}
}
int main()
{
while(scanf("%d %d",&n,&k)!=EOF)
{
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}