标签:
Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 61317 | Accepted: 19155 |
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
Source
1 #include <queue> 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 using namespace std; 6 7 const int maxn = 100000 + 5; 8 int vis[maxn], cnt[maxn]; 9 queue <int> q; 10 11 void Bfs() 12 { 13 int nx; 14 while(!q.empty()) 15 { 16 int x = q.front(); q.pop(); 17 for(int i = 0; i < 3; i++) //三种走法; 18 { 19 if(i == 0) nx = x + 1; 20 else if(i == 1) nx = x - 1; 21 else nx = 2 * x; 22 if(nx >= 0 && nx <= 100000 && !vis[nx]) //遍历到最后找最优?::剪枝? 23 { 24 vis[nx] = 1; 25 cnt[nx] = cnt[x] + 1; 26 q.push(nx); 27 } 28 } 29 } 30 } 31 32 int main() 33 { 34 int m, n; 35 while(~scanf("%d %d", &m, &n)) 36 { 37 if(m > n) 38 { 39 printf("%d\n", m - n); 40 return 0; 41 } 42 memset(vis, 0, sizeof(vis)); 43 vis[m] = 1; 44 cnt[m] = 0; 45 q.push(m); 46 Bfs(); 47 printf("%d\n", cnt[n]); 48 } 49 return 0; 50 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4708873.html