POJ 3278 Catch That Cow (有思路有细节的bfs)

时间:2021-04-15 00:24:12

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,先让你移动到k,有三种移动,—1,+1,*2。问你几步能到k。
最开始无脑搜,直接T了。后来发现bfs虽然是有点暴力的感觉但是还是要有思维在里面的!如果n>k,n只能一点点减到k。还有数组开大点,以防*2后越界。
代码如下:
 1 #include <cstdio>
2 #include <iostream>
3 #include <cstring>
4 #include <algorithm>
5 #include <cmath>
6 #include <queue>
7 using namespace std;
8 int n,k,ans;
9 bool vis[400010];
10 struct node
11 {
12 int pos,step;
13 };
14 bool check (int x)
15 {
16 if (vis[x])
17 return 0;
18 if (x<0||x>400010)
19 return 0;
20 else
21 return 1;
22 }
23 void bfs (node now)
24 {
25
26 queue<node>q;
27 q.push(now);
28 while (!q.empty())
29 {
30 node temp=q.front();
31 q.pop();
32 if (check(temp.pos-1))
33 {
34 node x;
35 x.pos=temp.pos-1;
36 x.step=temp.step+1;
37 vis[x.pos]=1;
38 if (x.pos==k)
39 {
40 ans=x.step;
41 return ;
42 }
43 q.push(x);
44 }
45 if (check(temp.pos+1)&&temp.pos<k)
46 {
47 node x;
48 x.pos=temp.pos+1;
49 x.step=temp.step+1;
50 vis[x.pos]=1;
51 if (x.pos==k)
52 {
53 ans=x.step;
54 return ;
55 }
56 q.push(x);
57 }
58 if (check(temp.pos*2)&&temp.pos<k)
59 {
60 node x;
61 x.pos=temp.pos*2;
62 x.step=temp.step+1;
63 vis[x.pos]=1;
64 if (x.pos==k)
65 {
66 ans=x.step;
67 return ;
68 }
69 q.push(x);
70 }
71 }
72 }
73 int main()
74 {
75 //freopen("de.txt","r",stdin);
76 while (~scanf("%d%d",&n,&k))
77 {
78 memset(vis,false,sizeof vis);
79 node now;
80 now.pos=n;
81 now.step=0;
82 ans=0;
83 if (n>=k)
84 printf("%d\n",n-k);
85 else
86 {
87 bfs(now);
88 printf("%d\n",ans);
89 }
90 }
91 return 0;
92 }