我有一个依赖图,其中一个节点需要满足前一个节点的两个副本。我想使用拓扑排序来获得评估顺序,但问题是拓扑排序忽略了并行/多边,并将其视为一个依赖。我在做错事情,或者我是否需要一个适用于多图的特定toposort?
答案 0 :(得分:2)
可以通过修改拓扑排序算法来完成。
原始算法存储没有传入边(S)的所有节点的集合,主要步骤是从S中取出一个节点,从S中删除它,并从图中删除所有边缘并检查是否有其他节点没有传入边缘。
将其更改为:从S获取一个节点,为每个邻居删除一个边缘实例,如果节点没有外出边缘从S中删除它,请检查是否有其他节点没有传入边缘。
来自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
更改算法:
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
take a node n from S
add n to tail of L
for each neighbouring node m of n
remove ONE edge (m,n) from the graph
if m has no other incoming edges then
insert m into S
if n doesn't have outgoing edges
remove n from S