8649 图的广度遍历

8649 图的广度遍历

时间限制:1000MS  内存限制:1000K
提交次数:1573 通过次数:975

题型: 编程题   语言: G++;GCC

 

Description

使用图的深度遍历实现的邻接表存储结构和基本操作函数,在此基础上实现图的广度遍历算法并加以测试。注意正确使用队列存储结构。




输入格式

第一行:输入0到3之间整数(有向图:0,有向网:1,无向图:2,无向网:3);
第二行:输入顶点数和边数;
第三行:输入各个顶点的值(字符型,长度〈3);(遍历从输入的第一个顶点开始)
第四行:输入每条弧(边)弧尾和弧头(以空格作为间隔),如果是网还要输入权值;



输出格式

输出对图广度遍历的结果



 

输入样例

0
3 3
a b c
a b
b c
c b



 

输出样例

a b c



 

提示




 

作者

 yqm

  SCAU数据结构课的一道oj题,,,因为懒.所以不想按学校发的那本数据结构书的方法来做,,而且也不考效率,于是就在题目里直接用STL的queue<>和stack<>来代替宽搜中要用到的队列和邻接表中的链表。。。代码量也就可以少很多了

  

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cmath>
 6 #include <cstdlib>
 7 #include <cctype>
 8 #include <queue>
 9 #include <stack>
10 #include <map>
11 #include <vector>
12 #include <set>
13 #include <utility>
14 #define ll long long
15 #define inf 0x3f3f3f3f
16 using namespace std;
17 
18 typedef struct node//表明顶点的结点,当然也可以直接用string
19 {
20     char name[4];
21 } node;
22 node temp;
23 stack<node> q[100005];//这里用栈来代替每个顶点所延伸出来的链表
24 char t1[4],t2[4];
25 int book[100005];
26 int v(char a[]) //该函数用来记录结点的字符串所对应的权值
27 {
28     if(strlen(a)==1)
29         return a[0];
30     else
31         return a[0]*122+a[1];
32 }
33 int main()
34 {
35     //freopen("input.txt","r",stdin);
36     memset(book,0,sizeof(book));
37     int type;
38     scanf("%d",&type);
39     int n,m,w;
40     node first;
41     scanf("%d%d",&n,&m);
42     for(int i=0; i<n; i++)
43     {
44         scanf("%s",t1);
45         if(i==0)
46         {
47             strcpy(first.name,t1);
48         }
49     }
50     while(m--)
51     {
52         if(type==1||type==3)
53             scanf("%d%s%s",&w,t1,t2);
54         else
55             scanf("%s%s",t1,t2);
56         if(type==2||type==3)//如果是无向图
57         {
58             strcpy(temp.name,t1);
59             q[v(t2)].push(temp);
60             strcpy(temp.name,t2);
61             q[v(t1)].push(temp);
62         }
63         else //如果是有向图
64         {
65             strcpy(temp.name,t2);
66             q[v(t1)].push(temp);
67         }
68     }
69     //
70     int tt;
71     queue<node> tq;//进行宽搜要用到的队列
72     tq.push(first);
73     while(!tq.empty())
74     {
75         tt=v(tq.front().name);
76         if(!book[tt])//标记是否已访问过该顶点
77         {
78             printf("%s ",tq.front().name);
79             book[tt]=1;
80         }
81         while(!q[tt].empty())//将该点所有出边加入队列
82         {
83             tq.push(q[tt].top());
84             q[tt].pop();
85         }
86         tq.pop();
87     }
88     return 0;
89 }

   最好呢。。还是能够掌握了书本上的用链表的方法的好,,,(好吧...我还是太懒了。。。)

posted @ 2016-05-26 17:19  爱喝可乐的咖啡  阅读(510)  评论(0编辑  收藏  举报