【HDOJ】2717 Catch That Cow

bfs。

 1 /* 2717 */
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <queue>
 7 using namespace std;
 8 
 9 #define MAXN 100001
10 
11 queue<int> Q;
12 int s[MAXN];
13 int n, k;
14 int ans;
15 
16 void bfs() {
17     int cur, nxt;
18     
19     while (!Q.empty())
20         Q.pop();
21     
22     memset(s, 0, sizeof(s));
23     
24     Q.push(n);
25     while (!Q.empty()) {
26         cur = Q.front();
27         Q.pop();
28         if (cur == k)
29             break;
30         nxt = cur - 1;
31         if (nxt>=0 && s[nxt]==0) {
32             Q.push(nxt);
33             s[nxt] = s[cur] + 1;
34         }
35         nxt = cur + 1;
36         if (nxt<MAXN && s[nxt]==0) {
37             Q.push(nxt);
38             s[nxt] = s[cur] + 1;
39         }
40         nxt = cur + cur;
41         if (nxt<MAXN && (nxt-k)<(k-cur) && s[nxt]==0) {
42             Q.push(nxt);
43             s[nxt] = s[cur] + 1;
44         }
45     }
46 }
47 
48 int main() {
49 
50 #ifndef ONLINE_JUDGE
51     freopen("data.in", "r", stdin);
52 #endif
53 
54     while (scanf("%d %d", &n, &k) != EOF) {
55         if (n >= k)
56             printf("%d\n", n-k);
57         else {
58             bfs();
59             printf("%d\n", s[k]);
60         }
61     }
62 
63     return 0;
64 }

 

posted on 2015-02-13 17:36  Bombe  阅读(139)  评论(0编辑  收藏  举报

导航