(六)拓扑排序 *

将任务的先后顺序用有向图表示,图中顶点代表任务。如果它是有向无环图(DAG),则可以拓扑排序。
例如:完成A任务要先完成B,C任务;完成B任务要先完成D任务;完成D任务要先完成C任务。
图 A
这里写图片描述
我们的目的是连续执行任务。即我们拓扑排序的结果
图 B

    C--> D--> B--> A

这样形成的一个任务序列,对任务有向图(图 A)的任意一条边(i, j),拓扑排序后(图B中)i 任务一定会出现在任务 j 前面。

下面有两种算法的伪代码
1. Kahn’s algorithm

L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
    remove a node n from S
    add n to tail of L
    for each node m with an edge e from n to m do
        remove edge e from the graph
        if m has no other incoming edges then
            insert m into S
if graph has edges then
    return error (graph has at least one cycle)
else 
    return L (a topologically sorted order)

2.Depth-first search

L ← Empty list that will contain the sorted nodes
while there are unmarked nodes do
    select an unmarked node n
    visit(n) 
function visit(node n)
    if n has a temporary mark then stop (not a DAG)
    if n is not marked (i.e. has not been visited yet) then
        mark n temporarily
        for each node m with an edge from n to m do
            visit(m)
        mark n permanently
        unmark n temporarily
        add n to head of L

to be continued

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值