Catch That Cow

Posted edviv

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Catch That Cow相关的知识,希望对你有一定的参考价值。

链接:https://vjudge.net/problem/POJ-3278

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 - 1 or + 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 <iostream>
 2 #include <queue>
 3 #include <cstring>
 4 #include <cstdio>
 5 using namespace std;
 6 const int N = 1e5;
 7 int n,k;
 8 int walk[N + 10];
 9 int main()
10 
11     scanf("%d%d",&n,&k);
12     queue<int> q;
13     q.push(n);//将起点加入队列
14     while(!q.empty())
15     
16         int now = q.front();
17         q.pop();
18         if(now == k)//找到就跳出
19         
20             printf("%d\\n",walk[k]);
21             break;
22         
23         //三种状态:+1,-1,*2
24         if(now - 1 >= 0 && !walk[now - 1])
25         
26             q.push(now - 1);
27             walk[now - 1] = walk[now] + 1;
28         
29         if(now + 1 <= N && !walk[now + 1])
30         
31             q.push(now + 1);
32             walk[now + 1] = walk[ now ] + 1;
33         
34         if(now*2 <= N && !walk[now*2])
35         
36             q.push(now*2);
37             walk[now*2] = walk[now] + 1;
38         
39     
40     return 0;
41 

 

以上是关于Catch That Cow的主要内容,如果未能解决你的问题,请参考以下文章

HDU 2717 Catch That Cow(bfs)

Catch That Cow

Catch That Cow

Catch That Cow

Catch That Cow

Catch That Cow