模板-宽度优先搜索的前向星实现

  接上篇。这次是bfs。不过使用的时候要注意别被环坑了!上代码。模板仅供参考。

 1 #include <cstdio>
 2 #include <vector>
 3 using namespace std;
 4 
 5 const int MAXN=100;
 6 int m,n;
 7 struct node {
 8     int to;
 9     int w;
10 };
11 vector <node> map[MAXN];
12 bool s[MAXN]={false};
13 int que[MAXN];
14 
15 void bfs(int x) {
16     int head=0,tail=0,cur;
17     que[tail++]=x;
18     s[x]=true;
19     while (head<tail && tail<n) {
20         cur=que[head];
21         vector <node>::iterator it;
22         for (it=map[cur].begin();it!=map[cur].end();it++) {
23             node tmp= *it;
24             if (!s[tmp.to]) {
25                 s[tmp.to]=true;
26                 que[tail++]=tmp.to;
27             }
28             if (tail>=n) break;
29         }
30         head++;
31     }
32 }
33 
34 int main() {
35     scanf("%d%d",&m,&n);
36     int k,i,j,w;
37     for (k=1;k<=m;k++) {
38         scanf("%d%d%d",&i,&j,&w);
39         node e;
40         e.to=j;
41         e.w=w;
42         map[i].push_back(e);
43     }
44     bfs(1);
45     for (i=0;i<n&&que[i]!=0;i++) printf("%d\n",que[i]);
46     return 0;
47 }

 

posted on 2017-10-07 19:55  Pyloj 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/wuyuema/p/7635623.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值