Catch That Cow(广度搜索BFS,队列)

Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64

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

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

题意:找回丢失的牛,输入人和牛在的位置,人和牛处于一条直线上,牛不动,人可以往前往后移动一步或者一次到达它的二倍处,比如初始位置在n,下一步可以为n-1;n+1;n*2;

问走几步找到牛。

 1 #include <iostream> 
 2 #include <queue> 
 3 #define SIZE 100001 
 4   
 5 using namespace std; 
 6   
 7 queue<int> x; 
 8 bool visited[SIZE]; //true and false
 9 int step[SIZE]; 
10   
11 int bfs(int n, int k)//广搜 
12 { 
13     int head, next; 
14     
15     x.push(n); //起始节点入队 
16      
17     visited[n] = true; //标记n已访问 
18      
19     step[n] = 0; //起始步数为0 
20      
21     while (!x.empty()) //队列非空时 
22     { 
23           
24         head = x.front(); //取出队头
25           
26         x.pop(); //弹出队头
27           
28         for (int i = 0; i < 3; i++) //3个方向搜索
29         { 
30             if (i == 0) next = head - 1; 
31             else if (i == 1) next = head + 1; 
32             else next = head * 2; 
33               
34             if (next > SIZE || next < 0) continue;//越界就不考虑了 
35            
36             if (!visited[next])  //判重  
37             { 
38                  
39                 x.push(next); //节点入队 
40                
41                 step[next] = step[head] + 1; //步数+1   
42                  
43                 visited[next] = true; //标记节点已访问 
44             } 
45             
46             if (next == k) return step[next]; //找到退出  
47         } 
48     } 
49 } 
50   
51 int main() 
52 { 
53     int n, k; 
54     cin >> n >> k; 
55     if (n >= k) 
56     { 
57         cout << n - k << endl; 
58     } 
59     else 
60     { 
61         cout << bfs(n, k) << endl; 
62     } 
63     return 0; 
64 } 

 

posted @ 2013-08-12 10:16  WangLC  阅读(268)  评论(0编辑  收藏  举报