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?
Input5 17
4
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
int book[100010];
int ans,x,k;
struct node
{
int x;
int step;
}a,b;
queue<node>Q;
void bfs()
{
int i;
while(!Q.empty())
{
a=Q.front();
Q.pop();
if(a.x==k)
{
ans=a.step;
return ;
}
else
{
for(i=0;i<3;i++)
{
if(i==0)
b.x=a.x+1;
if(i==1)
b.x=a.x-1;
if(i==2)
b.x=a.x*2;
b.step=a.step+1;
if(b.x<0||b.x>100000)
continue ;
if(book[b.x]==0)
{
book[b.x]=1;
Q.push(b);
}
}
}
}
return ;
}
int main()
{
while(~scanf("%d %d",&x,&k))
{
memset(book,0,sizeof(book));
a.x=x;
book[x]=1;
a.step=0;
Q.push(a);
bfs();
printf("%d\n",ans);
}
return 0;
}