【HDOJ】2717 Catch That Cow

本文详细介绍了一种经典的图搜索算法——宽度优先搜索(BFS)的实现原理与具体应用案例。通过对C++代码的深入剖析,帮助读者理解如何使用队列进行节点遍历,并解决寻找两点间最短路径的问题。

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 }

 

转载于:https://www.cnblogs.com/bombe1013/p/4290720.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值