Fellow me on GitHub

POJ3278(KB1-C 简单搜索)

Catch That Cow

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.

Source

USACO 2007 Open Silver

 

 1 //2017-02-22
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <queue>
 6 
 7 using namespace std;
 8 
 9 bool book[200005];
10 struct node
11 {
12     int pos, step;
13 };
14 
15 int main()
16 {
17     int n, k;
18     while(cin>>n>>k)
19     {
20         memset(book, 0, sizeof(book));
21         queue<node> q;
22         book[n] = 1;
23         node tmp;
24         tmp.pos = n;
25         tmp.step = 0;
26         q.push(tmp);
27         int pos, step;
28         while(!q.empty())
29         {
30             pos = q.front().pos;
31             step = q.front().step;
32             q.pop();
33             if(pos == k){
34                 cout<<step<<endl;
35                 break;
36             }
37             if(pos-1==k || pos+1==k || 2*pos==k)
38             {
39                 cout<<step+1<<endl;
40                 break;
41             }
42             if(pos >= 1 && !book[pos-1]){
43                 tmp.pos = pos-1;
44                 tmp.step = step+1;
45                 q.push(tmp);
46                 book[pos-1] = 1;
47             }
48             if(!book[pos+1]){
49                 book[pos+1] = 1;
50                 tmp.pos = pos+1;
51                 tmp.step = step+1;
52                 q.push(tmp);
53             }
54             if(2*pos<=200005&&!book[pos*2]){
55                 book[2*pos] = 1;
56                 tmp.pos = 2*pos;
57                 tmp.step = step+1;
58                 q.push(tmp);
59             }
60         }
61     }
62 
63     return 0;
64 }

 

posted @ 2017-02-22 12:11  Penn000  阅读(338)  评论(0编辑  收藏  举报