Catch That Cow (POJ - 3278)

题面

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?

输入

Line 1: Two space-separated integers: N and K

输出

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

样例输入

15 17

样例输出

14

提示

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,注意剪枝

代码

 1using namespace std;
 2typedef long long ll;
 3const int inf = 0x3f3f3f3f;
 4const int N = 1e5+5;
 5
 6bool vis[N] = {0};
 7int n, k, ans = 0;
 8
 9struct P {
10    int x;
11    int step;
12};
13
14int bfs() {
15    memset(vis, 0, sizeof(vis));
16
17    P sp;
18    sp.x = n;
19    sp.step = 0;
20
21    queue<P> q;
22    q.push(sp);
23    vis[sp.x] = 1;
24
25    while(!q.empty()) {
26        P tp = q.front();
27        q.pop();
28
29        if(tp.x==k) {
30            return tp.step;
31        }
32
33        P np = tp;
34
35        np.x = tp.x - 1;
36        if(np.x>=0 && !vis[np.x]) {
37            np.step = tp.step+1;
38            q.push(np);
39            vis[np.x] = 1;
40        }
41
42        np.x = tp.x + 1;
43        if(np.x<=N && !vis[np.x]) {
44            np.step = tp.step+1;
45            q.push(np);
46            vis[np.x] = 1;
47        }
48
49        np.x = tp.x * 2;
50        if(np.x<=N && !vis[np.x]) {
51            np.step = tp.step+1;
52            q.push(np);
53            vis[np.x] = 1;
54        }
55    }
56    return 0;
57}
58
59int main(void) {
60    scanf("%d%d", &n, &k);
61
62    if(n>k)
63        ans = n-k;
64    else
65        ans = bfs();
66
67    printf("%d\n", ans);
68    return 0;
69}