首页 > 其他 > 详细

Catch That Cow

时间:2019-09-01 01:00:56      阅读:98      评论:0      收藏:0      [点我收藏+]

链接: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

原文:https://www.cnblogs.com/Edviv/p/11440972.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!