sdutacm-数据结构实验之图论二:基于邻接表的广度优先搜索遍历

来源:互联网 发布:java图相关算法 编辑:程序博客网 时间:2024/06/10 23:55

数据结构实验之图论二:基于邻接表的广度优先搜索遍历

Time Limit: 1000MSMemory Limit: 65536KB

SubmitStatistic

ProblemDescription

给定一个无向连通图,顶点编号从0n-1,用广度优先搜索(BFS)遍历,输出从某个顶点出发的遍历序列。(同一个结点的同层邻接点,节点编号小的优先遍历)

Input

输入第一行为整数n0< n <100),表示数据的组数。
对于每组数据,第一行是三个整数kmt0k1000m(k-1)*k/20 tk),表示有m条边,k个顶点,t为遍历的起始顶点。
下面的m行,每行是空格隔开的两个整数uv,表示一条连接uv顶点的无向边。

Output

输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示BFS的遍历结果。

ExampleInput

1
6 7 0
0 3
0 4
1 4
1 5
2 3
2 4
3 5

ExampleOutput

0 3 4 2 5 1

Hint

用邻接表存储。

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: AcceptedTake time: 0msTake Memory: 2024KBSubmit time: 2017-02-15 15:15:16****************************************************/

0 0
原创粉丝点击