C - Catch That Cow POJ - 3278

 1 //标准bfs
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <queue>
 7 
 8 using namespace std;
 9 
10 int dir[3] = { 1, -1 };
11 
12 struct node
13 {
14     int x, step;
15 } s, ss;
16 
17 int bfs(int n, int k)
18 {
19     queue<node>q, qq;
20     s.x = n;
21     s.step = 0;
22     int vis[100010] = { 0 };
23     q.push(s);
24     while (!q.empty())
25     {
26         s = q.front();
27         q.pop();
28         if (s.x == k)
29             return s.step;
30         for (int i = 0; i < 2; i++)
31         {
32             ss.x = s.x + dir[i];
33             ss.step = s.step + 1;
34             if (ss.x >= 0 && ss.x <= 100000)
35             if (!vis[ss.x])
36             {
37                 vis[ss.x] = 1;
38                 q.push(ss);
39             }
40         }
41         ss.x = s.x * 2;
42         ss.step = s.step + 1;
43         if (ss.x >= 0 && ss.x <= 100000)
44         {
45             if (!vis[ss.x])
46             {
47                 vis[ss.x] = 1;
48                 q.push(ss);
49             }
50         }
51     }
52     return 0;
53 }
54 
55 int main()
56 {
57     int n, k;
58     while (~scanf("%d%d", &n, &k))
59     {
60         printf("%d\n", bfs(n, k));
61     }
62     return 0;
63 }

 

posted @ 2018-04-04 20:08  ouyang_wsgwz  阅读(175)  评论(0编辑  收藏  举报