实验 图的基本操作
来源:互联网 发布:适合送男生的礼物知乎 编辑:程序博客网 时间:2024/06/07 18:01
1、键盘输入数据,建立一个有向图的邻接表。
2、输出该邻接表。
3、在有向图的邻接表的基础上计算各顶点的度,并输出。
4、以有向图的邻接表为基础实现输出它的拓扑排序序列。
5、采用邻接表存储实现有向图的深度优先递归遍历。
6、采用邻接表存储实现有向图的广度优先遍历(利用队列实现)。
7、编写一个主函数,调试上述算法。
代码:
#include <bits/stdc++.h>using namespace std;const int MAXN=1e4;typedef struct Graph{ vector <int> edge[MAXN]; int n; int cntin[MAXN],cntout[MAXN]; bool vis[MAXN];public: void ini(){ int m,x,y; bool is_dir; cin>>n>>m>>is_dir; for(int i=1;i<=n;i++) edge[i].clear(),cntin[i]=cntout[i]=0; for(int i=1;i<=m;i++){ cin>>x>>y; edge[x].push_back(y); cntout[x]++;cntin[y]++; if(!is_dir) edge[y].push_back(x),cntin[x]++,cntout[y]++; } } void show(){ for(int i=1;i<=n;i++){ int len=edge[i].size(); cout<<i<<" :"; for(int j=0;j<len;j++) cout<<' '<<edge[i][j]; cout<<endl; } } void cnt(){ for(int i=1;i<=n;i++) cout<<i<<" :"<<cntin[i]+cntout[i]<<endl; } void Topology_Sequence(){ int cnt[n+1]; for(int i=1;i<=n;i++) cnt[i]=cntin[i]; queue <int> que; for(int i=1;i<=n;i++) if(cnt[i]==0) que.push(i); int now; while(!que.empty()){ now=que.front();que.pop(); cout<<now<<' '; int len=edge[now].size(); for(int i=0;i<len;i++){ cnt[edge[now][i]]--; if(cnt[edge[now][i]]==0) que.push(edge[now][i]); } } cout<<endl; } void dfs(int pos){ if(vis[pos]) return ; cout<<pos<<' '; vis[pos]=1; int len=edge[pos].size(); for(int i=0;i<len;i++) dfs(edge[pos][i]); } void Travel_dfs(){ memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) dfs(i); cout<<endl; } void Travel_bfs(){ memset(vis,0,sizeof(vis)); queue <int> que; for(int i=1;i<=n;i++) if(cntin[i]==0) que.push(i),vis[i]=1; int now; while(!que.empty()){ now=que.front();que.pop(); cout<<now<<' '; int len=edge[now].size(); for(int i=0;i<len;i++){ if(vis[edge[now][i]]==0) que.push(edge[now][i]),vis[edge[now][i]]=1; } } cout<<endl; }}Graph;int main(){ Graph a; a.ini(); a.cnt(); a.Topology_Sequence(); a.Travel_dfs(); a.Travel_bfs();}样例输入:
12 16 11 21 31 41 122 33 53 73 84 55 76 89 109 129 1110 1211 6
阅读全文
0 0
- 实验 图的基本操作
- 实验4 图的基本操作
- 栈的基本操作实验报告
- 实验五:二叉树的基本操作
- 实验十四 SCVMM虚拟机的基本操作
- 实验一 线性表的基本操作
- 数据结构实验报告单链表的基本操作
- 实验一:线性表的基本操作
- 栈实验之栈的基本操作
- [实验一] 顺序表的基本操作
- [实验二] 单链表的基本操作
- [实验五] 二叉树的基本操作
- Linux下VI的基本操作实验
- 实验 二叉树的基本操作
- 实验二 链表的基本操作
- 实验三 栈的基本操作
- 实验四 队列的基本操作
- 图的操作实验
- Android web输入框自动缩回软键盘
- CGI编程---CGI环境变量
- timer计时器的秒后跳转
- C# 复制一个DataTable的数据行
- 如何确定ArcGIS坡度分析中的Z因子
- 实验 图的基本操作
- Skill: 三星Galaxy S2 i9100g刷机
- ios 通过Category给系统类添加属性(关联值)
- Kafka分区策略及自定义
- 跳转控制语句---break,continue,return
- jQuery Mobile 触摸事件
- 微信支付接口的协议规则
- 将view添加到UIWidow两种方式的比较
- 2017-4-18 CCCC决赛总结