标签:des blog io ar os sp for 数据 on
1 6 7 0 0 3 0 4 1 4 1 5 2 3 2 4 3 5
0 3 4 2 5 1
代码:
#include <iostream> #include <string> #include <stdio.h> #include <string.h> #include <algorithm> #include <queue>; using namespace std; struct node { int data; int next; }a[6000]; int cnt; int head[101]; void Insert_edge(int u, int v) { a[cnt].data=u; a[cnt].next=head[v]; head[v]=cnt++; } int list[101],e; void bfs(int n, int s) //n个点, s是起点 { queue<int>q; bool vis[101]; memset(vis, false, sizeof(vis)); q.push(s); vis[s]=true; int i, dd; //当前队首元素 int ff; while(!q.empty()) { dd=q.front(); q.pop(); list[e++]=dd; int w[101], p=0; //queue<int>p; for(i=head[dd]; i!=-1; i=a[i].next ) { ff=a[i].data; if(vis[ff]==false) { //p.push(ff); w[p++]=ff; vis[ff]=true; } } sort(w, w+p); //排序 为了保证大小顺序 for(i=0; i<p; i++) { q.push(w[i]); //遍历结果加入队列 } } while(!q.empty()) { ff=q.front(); q.pop(); list[e++]=ff; } } int main() { int t; cin>>t; int i, j; int n, m, u, v; int start; while(t--) { cin>>n>>m>>start; cnt=0; memset(head, -1, sizeof(head)); for(i=0; i<m; i++) { cin>>u>>v; Insert_edge(u, v); Insert_edge(v, u); //无向图插入边 } bfs(n, start); for(i=0; i<e; i++) { if(i==0) cout<<list[i]; else cout<<" "<<list[i]; } cout<<endl; } return 0; }
标签:des blog io ar os sp for 数据 on
原文地址:http://www.cnblogs.com/yspworld/p/4122689.html