简体   繁体   English

检查有向无环图是否可行

[英]Check if directed acyclic graph is feasible

For a given directed acyclic graph G I'm looking for a way to verify if a list L , containing the activities, is precedence feasible.对于给定的有向无环图G我正在寻找一种方法来验证包含活动的列表L是否优先可行。 A resource-saving solution would be nice since the size of G may increase drastically.节省资源的解决方案会很好,因为G的大小可能会急剧增加。

Example:例子:

在此处输入图像描述

G = {0: [], 1: [0], 2: [0], 3: [0], 4: [1], 5: [1], 6: [4], 7: [4], 8: [3,6,7], 9: [2,5,6], 10: [2,5], 11: [8,9,10]}

Now this list现在这份清单

L1 = [0, 1, 2, 3, 4, 5, 10, 6, 7, 9, 8, 11]

for example is feasible but例如是可行的,但

L2 = [1, 0, 2, 3, 4, 10, 5, 6, 7, 9, 8, 11]

is not because activity 0 is a predecessor of 1 and activity 5 is a predecessor of 10.不是因为活动 0 是 1 的前身,而活动 5 是 10 的前身。

As I understand the question you want to check whether a given ordering of nodes is consistent with partial ordering defined by the edges in the graph.据我了解,您要检查给定的节点顺序是否与图中边缘定义的部分顺序一致。 Maybe I'm missing something, but for this it should be enough to check for all edges a ---> b that the index of a in the list is lower than the index of b .也许我遗漏了一些东西,但为此它应该足以检查所有边a ---> b列表中a的索引低于b的索引。 If you create a dictionary mapping elements to their positions first, the complexity for this will be only O(e) , e being the number of edges.如果您首先创建一个字典将元素映射到它们的位置,则复杂度将仅为O(e)e是边数。

def check(g, l):
    pos = {x: i for i, x in enumerate(l)} # for O(1) index
    return all(pos[a] < pos[b] for b in g for a in g[b])

G = {0: [], 1: [0], 2: [0], 3: [0], 4: [1], 5: [1], 6: [4],
     7: [4], 8: [3,6,7], 9: [2,5,6], 10: [2,5], 11: [8,9,10]}
L1 = [0, 1, 2, 3, 4, 5, 10, 6, 7, 9, 8, 11]
L2 = [1, 0, 2, 3, 4, 10, 5, 6, 7, 9, 8, 11]
print(check(G, L1)) # True
print(check(G, L2)) # False

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

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