Loading

POJ 3278 Catch That Cow

题目地址: https://vjudge.net/problem/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 - 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<cstring>   
 3 #include<stdio.h> 
 4 #include<queue>
 5 
 6 using namespace std;
 7 
 8 #define MAX 100000
 9 int N, K;
10 int vis[MAX + 20];
11 
12 struct node
13 {
14     int x;
15     int step;
16 }s;
17 
18 void bfs(int x)
19 {
20     memset(vis, 0, sizeof(vis));
21     s.x = x;
22     s.step = 0;
23     vis[x] = 1;
24     queue<node> Q;
25     Q.push(s);
26 
27     node t;
28     while (!Q.empty())
29     {
30         t = Q.front();
31         Q.pop();
32 
33         if (t.x == K)
34         {
35             cout << t.step << endl;
36             return;
37         }
38 
39         if (t.x + 1 <= MAX && !vis[t.x + 1])
40         {
41             s.x = t.x + 1;
42             s.step = t.step + 1;
43             vis[s.x] = 1;
44             Q.push(s);
45         }
46         if (t.x - 1 >= 0 && !vis[t.x - 1])
47         {
48             s.x = t.x - 1;
49             s.step = t.step + 1;
50             vis[s.x] = 1;
51             Q.push(s);
52         }
53         if (t.x * 2 <= MAX && !vis[t.x * 2])
54         {
55             s.x = t.x * 2;
56             s.step = t.step + 1;
57             vis[s.x] = 1;
58             Q.push(s);
59         }
60     }
61     return;
62 }
63 
64 int main()
65 {
66     while(cin >> N >> K)
67         bfs(N);
68 
69 
70     return 0;
71 }

 

posted @ 2019-02-18 12:05  拾月凄辰  阅读(198)  评论(0编辑  收藏  举报