Catch That Cow

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
 
struct node {
    int x;
    int step;
};
 
int n, k, vis[100010];
node s, e;
 
int bfs()
{
    queue<node> q;
    node t, p;
    s.x = n;
    s.step = 0;
    vis[s.x] = 1;
    q.push(s);
    while(!q.empty())
    {
        t = q.front();
        q.pop();
         
        if(t.x == e.x)  return t.step;
        if(t.x < 0 || t.x > 100000)
            continue;
         
        // 向右走一步
        if(t.x + 1 <= 100000 && vis[t.x + 1] == 0)
        {
            p.x = t.x + 1;
            p.step = t.step + 1;
            vis[p.x] = 1;
            q.push(p);
        }
         
        // 向左走一步
        if(t.x - 1 >= 0 && vis[t.x - 1] == 0)
        {
            p.x = t.x - 1;
            p.step = t.step + 1;
            vis[p.x] = 1;
            q.push(p);
        }
         
        // 向右走两倍步数
        if(t.x * 2 <= 100000 && vis[t.x * 2] == 0)
        {
            p.x = t.x * 2;
            p.step = t.step + 1;
            vis[p.x] = 1;
            q.push(p);
        }
    }
    return 0;
}
 
int main()
{
    int result;
    while(cin >> n >> k)
    {
        memset(vis, 0, sizeof(vis));
        s.x = n, e.x = k;
        result = bfs();
        cout << result << endl;
    }
    return 0;
}

  

posted @   青衫客36  阅读(148)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示