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
//STATUS:C++_AC_63MS_9564K
#include<stdio.h>
#include<memory.h>
int BFS();
const int MAXN=1100100;
int vis[200010],n,k,q[MAXN][2],d[2]={1,-1};
int main()
{
// freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&k)!=EOF)
{
memset(q,0,sizeof(q));
memset(vis,0,sizeof(vis));
k<=n?printf("%d\n",n-k):printf("%d\n",BFS());
}
return 0;
}
int BFS()
{
int i,front=0,rear=0,n1,n2,t;
q[rear++][0]=n;
vis[n]=1;
while(front<rear)
{
n1=q[front][0];
if(n1==k)return q[front][1];
t=q[front++][1]+1;
for(i=0;i<2;i++){
n2=n1+d[i];
if(!vis[n2]){
vis[n2]=1; //vis
q[rear][0]=n2;
q[rear++][1]=t;
}
}
if( k-n1>2*n1-k ){ //判断是否2*n的情况能否入队列
n2=2*n1;
if(!vis[n2]){
vis[n2]=1; //vis
q[rear][0]=n2;
q[rear++][1]=t;
}
}
}
return 0;
}