POJ 3278 Catch That Cow
Posted fengzeng666
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 3278 Catch That Cow相关的知识,希望对你有一定的参考价值。
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 129558 | Accepted: 40251 |
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
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 5 using namespace std; 6 7 #define MAX 100000 8 int visited[MAX+20]; 9 int lev[MAX+20]; //记录每个结点的层数 10 11 void BFS(int N, int K) 12 { 13 memset(visited, 0, sizeof(visited)); 14 memset(lev, 0, sizeof(lev)); 15 lev[N] = 0; 16 visited[N] = 1; 17 queue<int>Q; 18 Q.push(N); 19 20 while (!Q.empty()) 21 { 22 int v = Q.front(); 23 Q.pop(); 24 25 if (v == K) 26 cout << lev[v] << endl; 27 28 if (v+1 <= MAX && !visited[v + 1]) 29 { 30 lev[v + 1] = lev[v] + 1; 31 Q.push(v + 1); 32 visited[v + 1] = 1; 33 } 34 if (v-1 >= 0 && !visited[v - 1]) 35 { 36 lev[v - 1] = lev[v] + 1; 37 Q.push(v - 1); 38 visited[v - 1] = 1; 39 } 40 if (v * 2 <= MAX && !visited[v * 2]) 41 { 42 lev[v * 2] = lev[v] + 1; 43 Q.push(v * 2); 44 visited[v * 2] = 1; 45 } 46 } 47 48 } 49 50 int main() 51 { 52 int N, K; 53 while (cin >> N >> K) 54 { 55 BFS(N, K); 56 } 57 58 59 return 0; 60 }
以上是关于POJ 3278 Catch That Cow的主要内容,如果未能解决你的问题,请参考以下文章