求拓扑序列

本文介绍了如何求解有向图的拓扑序列,指出拓扑序列常用于判断有向无环图(DAG)的存在。通过步骤描述了求拓扑序列的过程,包括寻找入度为0的点,删除点及其关联边,以及利用数组和队列等数据结构进行辅助操作。强调了数据结构在算法实现中的关键作用。
摘要由CSDN通过智能技术生成

求一个有向图的拓扑序列也是图论的基本题型。但是一般不会显式的看出题意是求拓扑序列或者求是否存在拓扑序列。拓扑序列一般用来判断一个图是否是一个有向无环图,如果一个图存在符合拓扑次序的序列则该图是有向无环图,反之则不是。

求拓扑序列步骤:

1,找到一个入度为0的点作为拓扑序列的第一个点

2,把该点和该点所有的边从图中删去

3,再在新的图中选择一个入度为0的点作为拓扑系列的第二个点

...以此类推,如果在所有节点尚未删去时找不到入度为0的点则说明剩余节点存在环路,不存在拓扑序列

九度1448:Legal or Not 题目地址:http://ac.jobdu.com/problem.php?pid=1448 题目描述:

ACM-DIY is a large QQ group where many excellent acmers get together. It is so harmonious that just like a big family. Every day,many "holy cows" like HH, hh, AC, ZT, lcc, BF, Qinz and so on chat on-line to exchange their ideas. When someone has questions, many warm-hearted cows like Lost will come to help. Then the one being helped will call Lost "master", and Lost will have a nice "prentice". By and by, there are many pairs of "master and prentice". But then problem occurs: there are too many masters and too many prentices, how can we know whether it is legal or not?We all know a master can have many prentices and a prentice may have a lot of masters too, it's legal. Nevertheless,some cows are not so honest, they hold illegal relationship. Take HH and 3xian for instant, HH is 3xian's master and, at the same time, 3xian is HH's master,which is quite illegal! To avoid this,please help us to judge whether their relationship is legal or not. Please note that the "master and prentice" relation is transitive. It means that if A is B's master ans B is C's master, then A is C's master.

输入:
对于带权图,不能直接使用拓扑排序算法拓扑序列。需要进行一些修改。 首先,我们需要定义一个数组 $dist$,表示从起点到该点的最长路径长度。初始时,$dist[i]$ 的值应为 $-\infty$,表示还没有遍历到该点。 然后,我们对图进行拓扑排序。在每个点 $u$ 被遍历到时,更新其所有出边指向的点 $v$ 的 $dist$ 值,即 $dist[v] = \max(dist[v], dist[u] + w(u, v))$,其中 $w(u, v)$ 表示边 $(u, v)$ 的权值。 最后,按照拓扑排序的结果,按照 $dist$ 值从大到小进行排序即可得到带权图的拓扑序列。 代码实现如下: ```python from collections import deque def topological_sort(graph, indegree): n = len(graph) queue = deque() for i in range(n): if indegree[i] == 0: queue.append(i) order = [] while queue: u = queue.popleft() order.append(u) for v in graph[u]: indegree[v] -= 1 if indegree[v] == 0: queue.append(v) return order def weighted_topological_sort(graph, indegree, weights): n = len(graph) dist = [-float('inf')] * n dist[0] = 0 order = topological_sort(graph, indegree) order.sort(key=lambda u: -dist[u]) for u in order: for v, w in graph[u]: dist[v] = max(dist[v], dist[u] + weights[(u, v)]) return order ``` 其中,$graph$ 表示图的邻接表,$indegree$ 表示每个点的入度,$weights$ 是一个字典,表示每条边的权值。函数 $topological\_sort$ 是普通的拓扑排序算法,$weighted\_topological\_sort$ 则是带权图的拓扑排序算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值