Catch That Cow Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 10575 Accepted Submission(s): 3303
Problem 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.
Source |
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 long long l,k; 7 const int maxn=100000; 8 bool v[100010]; 9 struct node 10 { 11 long long x; 12 int step; 13 }; 14 bool check(long long a) 15 { 16 if(a<0||a>maxn||v[a]) return false; 17 return true; 18 } 19 int bfs() 20 { 21 node n,m; 22 n.x=l; 23 n.step=0; 24 queue<node> q; 25 q.push(n); 26 v[n.x]=1; 27 while(!q.empty()){ 28 n=q.front(); 29 q.pop(); 30 if(n.x==k) return n.step; 31 //-1 32 m.x=n.x-1; 33 if(check(m.x)){ 34 m.step=n.step+1; 35 v[m.x]=1; 36 q.push(m); 37 } 38 //+1 39 m.x=n.x+1; 40 if(check(m.x)){ 41 m.step=n.step+1; 42 v[m.x]=1; 43 q.push(m); 44 } 45 //*2 46 m.x=n.x*2; 47 if(check(m.x)){ 48 m.step=n.step+1; 49 v[m.x]=1; 50 q.push(m); 51 } 52 } 53 return -1; 54 } 55 int main() 56 { 57 while(cin>>l>>k){ 58 memset(v,0,sizeof(v)); 59 cout<<bfs()<<endl; 60 } 61 return 0; 62 }