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
* 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
Farmer John starts at point 5 and the fugitive cow is at point 17.
Sample Output
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #define maxn 201000 7 #define maxm 400000 8 #define ll long long 9 #define inf 1000000000 10 using namespace std; 11 struct edge{int go,next,w;}e[2*maxm]; 12 int n,m,k,s,t,tot,q[maxn],d[maxn],head[maxn]; 13 bool v[maxn]; 14 void ins(int x,int y) 15 { 16 e[++tot].go=y;e[tot].w=1;e[tot].next=head[x];head[x]=tot; 17 } 18 void insert(int x,int y) 19 { 20 ins(x,y);ins(y,x); 21 } 22 void spfa() 23 { 24 for(int i=1;i<=m;++i) d[i]=inf; 25 memset(v,0,sizeof(v)); 26 int l=0,r=1,x,y;q[1]=n;d[n]=0; 27 while(l!=r) 28 { 29 x=q[++l];if(l==maxn)l=0;v[x]=0; 30 for(int i=head[x];i;i=e[i].next) 31 if(d[x]+e[i].w<d[y=e[i].go]) 32 { 33 d[y]=d[x]+e[i].w; 34 if(!v[y]){v[y]=1;q[++r]=y;if(r==maxn)r=0;} 35 } 36 } 37 } 38 int main(){ 39 scanf("%d%d",&n,&k); 40 if(k<=n){printf("%d",abs(k-n));return 0;} 41 m=k+abs(k-n)+1; 42 for(int i=0;i<m;i++)insert(i,i+1); 43 for(int i=1;i<=m/2;i++)ins(i,i*2); 44 spfa(); 45 printf("%d",d[k]); 46 return 0; 47 }