博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从0开始 图论学习 拓扑排序 链式前向星表示法
阅读量:4321 次
发布时间:2019-06-06

本文共 1374 字,大约阅读时间需要 4 分钟。

拓扑排序

writer:pprp

分析:

建立一个队列,将所有入度为0的节点放到队列中

输出该节点,更新与其相连的其他点的入度

再次将所有更新节点中入度为0的点加入队列

算法思路:

每次选取一个入度为0的点,将其从该图中删除,再按照以上步骤进行依次删除,如果不能删除那么说明存在环状结构导致没有入度为0的点,将每次删除的点记录在一个vector数组中,最后进行输出

代码如下:

#include 
#include
#include
#include
//图的拓扑排序using namespace std;const int maxn = 1000;int vv,ee;struct node{ int to; int w; int next;};queue
qu;node edge[maxn];int head[maxn];int indegree[maxn];/*@declare:建立一个队列,将所有入度为0的节点放到队列中输出该节点,更新与其相连的其他点的入度再次将所有更新节点中入度为0的点加入队列*/vector
vt;void dfs(){ int cnt = 0; for(int i = 0 ; i < vv ; i++) if(indegree[i] == 0) qu.push(i), vt.push_back(i); while(!qu.empty()) { int x = qu.front(); qu.pop(); for(int k = head[x]; k != -1 ; k = edge[k].next) { indegree[edge[k].to]--; if(indegree[edge[k].to] == 0) { qu.push(edge[k].to); vt.push_back(edge[k].to); } } }}int main(){ freopen("in.txt","r",stdin); int x, y,z ; cin >> vv >> ee; memset(head,-1,sizeof(head)); memset(indegree,0,sizeof(indegree)); for(int i = 0 ; i < ee; i++) { cin >> x >> y >> z; edge[i].to = y; edge[i].w = z; edge[i].next = head[x]; head[x] = i; indegree[y]++; } dfs(); for(int i = 0; i < vt.size(); i++) cout << vt[i] << " "; cout << endl; return 0;}/*9 80 1 10 2 10 3 11 4 12 5 12 6 13 7 13 8 1*/

转载于:https://www.cnblogs.com/pprp/p/7788908.html

你可能感兴趣的文章
MYSQL GTID使用运维介绍(转)
查看>>
Fail to start neutron-server
查看>>
景安快运挂在磁盘-支持宝塔
查看>>
word中交叉引用不能更新的解决方法
查看>>
高性能HTTP加速器Varnish(概念篇)
查看>>
Linux 如何写makefile文件
查看>>
flutter_webview_plugin 无法加载网页的异常处理
查看>>
bloc控制读写文件
查看>>
微信小程序
查看>>
洛谷 P1059 明明的随机数
查看>>
window自动任务实现数据库定时备份
查看>>
Windows 7 Ultimate(旗舰版)SP1 32/64位官方原版下载(2011年5月12日更新版)
查看>>
javascript操作cookie
查看>>
深入理解HTTP协议(转)
查看>>
NHibernate讲解
查看>>
Android开发环境搭建(原创)
查看>>
js / jquery 获取和设置 FCK Editor 的值
查看>>
剑指offer-二叉树中和为某一值的路径
查看>>
grid - 网格项目跨行或跨列
查看>>
2019年2月
查看>>