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<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<math.h>
using namespace std;
const int maxn=1000000+5;
int n,m;
bool vst[maxn];
struct node
{
int x,step;
}t;
void bfs(struct node b)
{
queue <struct node> q;
struct node now,next;
b.step=0;
q.push(b);
while(!q.empty())
{
now=q.front();
if(now.x==m)
{
printf("%d\n",now.step);
return;
}
next.step=now.step+1;
for(int i=0;i<3;i++)//三种情况循环三次
{
if(i==0)
{
next.x=now.x+1;//生成新的坐标
if(!vst[next.x]&&next.x>=0&&next.x<=100000)//检查坐标是否越界是否走过
{
q.push(next);
vst[next.x]=1;
}
}
else if(i==1)
{
next.x=now.x-1;
if(!vst[next.x]&&next.x>=0&&next.x<=100000)
{
q.push(next);
vst[next.x]=1;
}
}
else
{
next.x=2*now.x;
if(!vst[next.x]&&next.x>=0&&next.x<=100000)
{
q.push(next);
vst[next.x]=1;
}
}
}
q.pop();
}
return;
}
int main()
{
while(scanf("%d%d",&t.x,&m)!=EOF)
{
for(int i=0;i<100010;i++)
{
vst[i]=0;
}
if(t.x>=m)
printf("%d\n",t.x-m);
else
bfs(t);
}
return 0;
}