HDU2717 Catch That Cow ( BFS )

 

Catch That Cow

Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

 

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

 


 

 

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. 


 
 Analysis
 
  从一个点到另一个点,每一步有多种走法,这是典型的 bfs 问题。
 
 
Tips
  •  注意数组开的够不够大
  •  在每一次开始判断是否已经搜到解

 

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include<queue>
 4 
 5 using namespace std;
 6 
 7 int vis[120000];
 8 int n,k,flag;
 9 
10 struct Node
11 {
12     int x;
13     int tm;
14 }root;
15 
16 void bfs()
17 {
18     memset(vis,0,sizeof(vis));
19     queue<Node>que;
20     que.push(root);
21 
22     vis[root.x] = 1;
23     int ans=100005;
24 
25     while(!que.empty())
26     {
27         Node q = que.front();
28         que.pop();
29 
30         //printf("q.x = %d\n",q.x);
31 
32         if(q.x == k )
33         {
34             ans = q.tm;
35             flag = 1;
36             break;
37         }
38 
39         Node q1,q2,q3;
40 
41         if(q.x+1 < 100005 &&!vis[q.x + 1]   )
42         {
43             //printf("q2.x = %d\n",q.x+1);
44             q2.x = q.x + 1;
45             q2.tm = q.tm + 1;
46 
47             vis[q2.x] = 1;
48             que.push(q2);
49         }
50 
51         if(q.x-1 >=0 && !vis[q.x - 1]   )
52         {
53             //printf("q1.x = %d\n",q.x-1);
54             q1.x = q.x - 1;
55             q1.tm = q.tm + 1;
56 
57             vis[q1.x] = 1;
58             que.push(q1);
59         }
60 
61 
62 
63         if(q.x *2 <100005 && !vis[q.x *2]   )
64         {
65             //printf("q3.x = %d\n",q.x*2);
66             q3.x = q.x *2;
67             q3.tm = q.tm + 1;
68 
69             vis[q3.x] = 1;
70             que.push(q3);
71 
72         }
73     }
74     if(flag) printf("%d\n",ans);
75     //else printf("-1\n");
76 }
77 
78 
79 int main()
80 {
81 
82     while(~scanf("%d%d",&n,&k))
83     {
84         flag = 0;
85 
86         root.x = n;
87         root.tm = 0;
88 
89         bfs();
90     }
91 
92     return 0;
93 }

 

posted @ 2015-07-28 10:43  Numerz  阅读(210)  评论(0编辑  收藏  举报