Catch That Cow
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
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
#include<stdio.h>
#include<string.h>
struct note {
int x;
int step;
};
int main() {
struct note que[100005];
int book[100005];
int next[4][2]= {{0,1},{1,0},{-1,0},{0,-1}};
int head,tail;
int i,j,k,n,m,startx,starty,q,p,tx,ty,flag;
while(scanf("%d %d",&n,&m)!=EOF){
if(n>=m)
printf("%d\n",n-m);
else{
memset(book,0,sizeof(book));
head=1;
tail=1;
que[tail].x=n;
que[tail].step=0;
tail++;
book[n]=1;
flag=0;
while(head<tail) {
for(k=0; k<3; k++) {
if(k==0)
tx=que[head].x-1;
else if(k==1)
tx=que[head].x+1;
else
tx=que[head].x*2;
if(tx>=0&&tx<=100000&&book[tx]==0) {
book[tx]=1;
que[tail].x=tx;
que[tail].step=que[head].step+1;
tail++;
}
if(tx==m) {
flag=1;
break;
}
}
if(flag==1)
break;
head++;
}
printf("%d\n",que[tail-1].step);
}
}
}