Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 37622 | Accepted: 11666 |
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
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<iostream> 5 const int M=100001; 6 using namespace std; 7 int vis[M]; 8 int step[M]; 9 queue<int>q; 10 11 void bfs(int n,int k) 12 { 13 int r,l;int t=0; 14 q.push(n); 15 vis[n]=1; 16 step[n]=0; 17 while(!q.empty()) 18 { 19 r=q.front(); 20 q.pop(); 21 for(int i=0;i<=2;i++) 22 { 23 if(i==0)l=r-1; 24 else if(i==1)l=r+1; 25 else if(i==2)l=r*2; 26 if(l>M||l<0) 27 continue; 28 if(!vis[l]) 29 { 30 q.push(l); 31 step[l]=step[r]+1; 32 vis[l]=1; 33 } 34 if(l==k) 35 { 36 t=1;break; 37 } 38 } 39 if(t==1)break; 40 } 41 printf("%d\n",step[l]); 42 } 43 44 int main() 45 { 46 int n,k; 47 scanf("%d %d",&n,&k); 48 if(n>=k) 49 printf("%d\n",n-k); 50 else bfs(n,k); 51 return 0; 52 }