我有一个依赖关系图,其中一个节点需要满足前一个节点的两个副本。我想使用拓扑排序来获取求值顺序,但问题是拓扑排序忽略了并行/多边,而只是将其视为一个依赖项。我建模错误,还是需要与多重图一起使用的特定拓扑?
可以通过修改拓扑排序算法来完成。
原始算法存储所有没有传入边(S)的节点的集合,主要步骤是从S中取出一个节点,将其从S中删除,并从图形中删除其所有边,并检查是否有其他没有传入边的节点。
将其更改为:从 S 中获取一个节点,将边缘的一个实例删除到每个邻居,如果节点没有传出边,则从 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
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