HDU 2717.Catch That Cow

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. 
         


由于移动方式只有 +1 -1 *2 因此如果 起点大于终点,直接相减即可

剩下就是标准的BFS模板


 1 /*
 2 By:OhYee
 3 Github:OhYee
 4 Email:oyohyee@oyohyee.com
 5 Blog:http://www.cnblogs.com/ohyee/
 6 
 7 かしこいかわいい?
 8 エリーチカ!
 9 要写出来Хорошо的代码哦~
10 */
11 
12 #include <cstdio>
13 #include <algorithm>
14 #include <cstring>
15 #include <cmath>
16 #include <string>
17 #include <iostream>
18 #include <vector>
19 #include <list>
20 #include <queue>
21 #include <stack>
22 using namespace std;
23 
24 //DEBUG MODE
25 #define debug 0
26 
27 //循环
28 #define REP(n) for(int o=0;o<n;o++)
29 
30 const int maxn = 100005;
31 
32 int BFS(int s,int v) {
33     if(s == v)
34         return 0;
35     if(s > v)
36         return s - v;
37 
38     queue<int> Q;
39     bool visited[maxn];
40     memset(visited,false,sizeof(visited));
41     int dis[maxn];
42     memset(dis,0,sizeof(dis));
43 
44     Q.push(s);
45     visited[s] = true;
46     while(!Q.empty()) {
47         int th = Q.front();
48         Q.pop();
49 
50         //达到终点
51         if(th == v)
52             break;
53 
54         //拓展节点
55 
56         #define push \
57         if(next > maxn || next <= 0) \
58             continue;\
59         if(!visited[next]) {\
60             Q.push(next);\
61             visited[next] = true;\
62             dis[next] = dis[th] + 1;\
63         }\
64 
65 
66         int next;
67         next = th + 1;
68         push;
69         next = th - 1;
70         push;
71         next = th * 2;
72         push;
73     }
74 
75     if(dis[v])
76         return dis[v];
77     else
78         return -1;
79 }
80 
81 bool Do() {
82     int s,v;
83     if(scanf("%d%d",&s,&v)==EOF)
84         return false;
85     printf("%d\n",BFS(s,v));
86     return true;
87 }
88 
89 int main() {
90     while(Do());
91     return 0;
92 }

 



posted @ 2016-04-14 00:25  OhYee  阅读(185)  评论(0编辑  收藏  举报