简体   繁体   English

将有向无环图转换为序列的算法

[英]Algorithm to convert directed acyclic graphs to sequences

If D depends on B and C which each depend on A, I want ABCD (or ACBD) as the result; 如果D依赖于B和C,而B和C都依赖于A,则我想要ABCD(或ACBD)作为结果; that is generate a flat sequence from the graph such that all nodes appear before any of their descendants. 即从图生成平面序列,以使所有节点都出现在其任何后代之前。 For example, we may need to install dependencies for X before installing X. 例如,在安装X之前,我们可能需要为X安装依赖项。

What is a good algorithm for this? 有什么好的算法?

In questions like this, terminology is crucial in order to find the correct links. 在这样的问题中,术语对于找到正确的链接至关重要。

The dependencies you describe form a partially ordered set (poset). 您描述的依赖项形成了部分排序的集合 (姿势)。 Simply put, that is a set with an order operator, for which the comparison of some pairs might be undefined. 简而言之,这是一个带有订单运算符的集合,对于这些集合,某些对的比较可能不确定。 In your example B and C are incomparible (neither B depends on C , nor C depends on B ). 在您的示例中BC是不可比的( B都不依赖C ,或者C都不依赖B )。

An extension of the order operator is one that respects the original partial order and adds some extra comparisons to previously incomparable elements. 订单运算符的扩展是一种尊重原始部分订单并为以前不可比拟的元素添加一些额外比较的扩展。 In the extreme: a linear extension leads to a total ordering. 在极端情况下: 线性扩展会导致整体排序。 For every partial ordering such an extension exists . 对于每个部分排序,都存在这种扩展

Algorithms to obtain a linear extension from a poset are called topological sorting . 从位姿获得线性扩展的算法称为拓扑排序 Wikipedia provides the following very simple algorithm : Wikipedia提供以下非常简单的算法

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM