【问题标题】:How to represent a dependency graph with alternative paths如何用替代路径表示依赖图
【发布时间】:2014-10-29 23:19:00
【问题描述】:

在这种情况下,我在尝试表示和操作依赖图时遇到了一些麻烦:

  • 一个节点有一些需要解决的依赖关系
  • 每条路径都不能有依赖循环(如 DAG 图中)
  • 每个依赖项都可以由多个其他节点解决

我从目标节点开始递归查找它的依赖关系,但必须保持上述属性,尤其是第三个。

这里只是一个小例子:

我想要一个像下面这样的图表

           (A)
          /   \
         /     \
        /       \
  [(B),(C),(D)] (E)
   /\        \
  /  \       (H)
(F)  (G)

意思是:

  • F、G、C、H、E 没有依赖关系
  • D 依赖于 H
  • B 依赖于 F 和 G
  • A 依赖于 E
    • B
    • C
    • D

所以,如果我写下所有可能的拓扑排序路径到 A 我应该有:

  1. E -> F -> G -> B -> A
  2. E -> C -> A
  3. E -> H -> D -> A

如何使用这些属性对图形进行建模?哪种数据结构更适合这样做?

【问题讨论】:

  • 这取决于你想对图表做什么。
  • 另外,F、E、H、D、A 等不也是有效的 topsorts 吗?
  • 是的,还有其他有效的顶级排序。我只写了几个例子。

标签: algorithm data-structures graph dependencies


【解决方案1】:

您应该使用带有附加属性的普通邻接列表,其中一个节点知道它的其他节点也将满足相同的依赖关系。这意味着 B、C、D 都应该知道它们属于同一个等价类。您可以通过将它们全部插入一个集合来实现这一点。

Node:
    List<Node> adjacencyList
    Set<Node> equivalentDependencies

要在拓扑排序中使用此数据结构,每当您删除源并删除其所有出边时,还要删除其等价类中的节点及其出边,并递归删除指向它们的节点. 来自维基百科:

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 o in the equivalency class of n <===removing equivalent dependencies
        remove j from S
            for each node k with an edge e from j to k do
                remove edge e from the graph
                if k has no other incoming edges then
                    insert k into S    
    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)

此算法将为您提供修改后的拓扑排序路径之一。

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 2013-09-07
    相关资源
    最近更新 更多