B - Catch That Cow (抓牛)
B - Catch That Cow
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64uDescription
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.
//用bfs,从当前位置开始,不断的试探,+1,-1,*2。直到找到牛,农民位置大于牛的时候,直接输出农民位置减牛的位置就行。
1 #include <stdio.h>
2 #include <string.h>
3 #include <queue>
4 using namespace std;
5
6 const int N = 1000000;
7 int map[N+10];
8 int n,k;
9
10 struct node
11 {
12 int x,step;
13 };
14
15 int check(int x)
16 {
17 if(x<0 || x>=N || map[x])
18 return 0;
19 return 1;
20 }
21
22 int bfs(int x)
23 {
24 queue <node> Q;
25 node a,next;
26
27 a.x = x;
28 a.step = 0;
29 map[x] = 1;
30 Q.push(a);
31
32 while(!Q.empty())
33 {
34 a = Q.front();
35 Q.pop();
36
37 if(a.x == k)
38 return a.step;
39 next = a;
40 //每次都将三种状况加入队列之中
41 next.x = a.x+1;
42 if(check(next.x))
43 {
44 next.step = a.step+1;
45 map[next.x] = 1;
46 Q.push(next);
47 }
48 next.x = a.x-1;
49 if(check(next.x))
50 {
51 next.step = a.step+1;
52 map[next.x] = 1;
53 Q.push(next);
54 }
55 next.x = a.x*2;
56 if(check(next.x))
57 {
58 next.step = a.step+1;
59 map[next.x] = 1;
60 Q.push(next);
61 }
62 }
63 return 0;
64 }
65
66 int main()
67 {
68 int ans;
69 while(scanf("%d%d",&n,&k)!=EOF)
70 {
71 memset(map,0,sizeof(map));
72 if (n>k) ans=n-k;
73 else ans = bfs(n);
74 printf("%d\n",ans);
75 }
76 return 0;
77 }