sdutacm-数据结构实验之图论二:基于邻接表的广度优先搜索遍历
数据结构实验之图论二:基于邻接表的广度优先搜索遍历
Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic
PRoblemDescription
给定一个无向连通图,顶点编号从0到n-1,用广度优先搜索(BFS)遍历,输出从某个顶点出发的遍历序列。(同一个结点的同层邻接点,节点编号小的优先遍历)
Input
输入第一行为整数n(0< n <100),表示数据的组数。 对于每组数据,第一行是三个整数k,m,t(0<k<100,0<m<(k-1)*k/2,0< t<k),表示有m条边,k个顶点,t为遍历的起始顶点。 下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。
Output
输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示BFS的遍历结果。
ExampleInput
16 7 00 30 41 41 52 32 43 5ExampleOutput
0 3 4 2 5 1Hint
用邻接表存储。
Author
#include <iostream> #include<bits/stdc++.h> using namespace std; int k,m,t; int ans[222],top,vis[222]; struct node { int data; struct node*next; }*a[500001]; void add(int i,int j) { struct node*q; q = new node; q->next = NULL; q->data = j; if(a[i]==NULL) { a[i] = q; } else { q->next = a[i]->next; a[i]->next = q; } } void bfs(int t,int n) { for(int i=0;i<m;i++) { for(node*p = a[i];p;p=p->next) { for(node*q = p->next;q;q=q->next) { if(p->data>q->data) swap(p->data,q->data); } } } /* for(int i=0;i<m;i++) { for(node*p = a[i];p;p=p->next) { printf("%d ",p->data); } printf("\n"); }*/ queue<int>q; q.push(t); vis[t] = 1; while(!q.empty()) { int h = q.front(); ans[top++] = q.front(); q.pop(); for(node*p = a[h];p;p=p->next) { if(vis[p->data]==0) { vis[p->data] = 1; q.push(p->data); } } } } int main() { int n,v,u; cin>>n; while(n--) { cin>>k>>m>>t; memset(a,0,sizeof(a)); memset(vis,0,sizeof(vis)); for(int i=1;i<=m;i++) { scanf("%d%d",&v,&u); add(v,u); add(u,v); } /*for(int i=0;i<m;i++) { for(node*p = a[i];p;p=p->next) { printf("%d ",p->data); } printf("\n"); }*/ top = 0; bfs(t,k); for(int i=0;i<k;i++) { printf("%d",ans[i]); if(i!=k-1) printf(" "); else printf("\n"); } } return 0; } /*************************************************** User name: jk160505徐红博 Result: Accepted Take time: 0ms Take Memory: 2024KB Submit time: 2017-02-15 15:15:16 ****************************************************/