由于 A、B、C、E 形成一个菱形,要将其转换为一棵树,我需要将 B 和 C 移动成一条线。
我尝试了以下操作:
拓扑路径为我们提供了一条直线路径。但是,如果可能,我想保留序列,即 A -> D。但是,如果有一个菱形,我希望一个节点只有一个父节点并且对这些父节点进行排序。
对于上述情况,有没有办法从 DAG 生成一棵树?
答案 0 :(得分:1)
Run a topological sort on the graph
For every node B, in reverse order of the topological sort:
If B has more than one parent:
Order its parents A1, A2, ..., An in the order of the topological sort
For every i in 1..n-1:
Add an arc from Ai to A(i+1)
Remove the arc from Ai to B
O(N^2)
,其中 N
是节点数这证明算法终止,并且每个节点在执行算法后至多有一个父节点。由于我们只从具有多个父节点的节点中删除父节点,因此我认为这也满足了您的问题。