Problem
There are two subclasses of graphs that automatically exclude the possibility of negative cycles: graphs without negative edges, and graphs without cycles. We already know how to efficiently handle the former (see the problem “Negative Weight Cycle”). We will now see how the single-source shortest-path problem can be solved in just linear time on directed acyclic graphs.
As before, we need to perform a sequence of updates (recall Bellman-Ford algorithm) that includes every shortest path as a subsequence. The key source of efficiency is that
Therefore, it is enough to linearize (that is, topologically sort) the DAG by depth-first search, and then visit the vertices in sorted order, updating the edges out of each. The algorithm is given below.
Notice that our scheme doesn’t require edges to be positive. In particular, we can find longest paths in a DAG by the same algorithm: just negate all edge lengths.
Source: Algorithms by Dasgupta, Papadimitriou, Vazirani. McGraw-Hill. 2006.
Given: A weighted DAG with integer edge weights from to and vertices in the edge list format.
Return: An array where is the length of a shortest path from the vertex to the vertex (). If is not reachable from set to x
.
图的两个子类自动排除负循环的可能性:没有负边的图和没有循环的图。我们已经知道如何有效处理前者(请参阅“负重循环”问题)。现在,我们将看到如何在有向无环图上仅在线性时间内解决单源最短路径问题。
和以前一样,我们需要执行一个更新序列(回想Bellman-Ford算法),其中包括每个最短路径作为子序列。效率的关键来源是
因此,足以通过深度优先搜索线性化(即,对拓扑进行排序)DAG ,然后按排序顺序访问顶点,从而更新每个顶点的边。该算法如下。
注意,我们的方案不需要边为正。尤其是,我们可以通过相同的算法在DAG中找到 最长的路径:只需取消所有边长即可。
资料来源:Dasgupta,Papadimitriou,Vazirani的算法。麦格劳-希尔。2006年。
返回:数组 哪里 是从顶点开始的最短路径的长度 到顶点 ()。如果 从以下位置无法到达 组 到x
。
Sample Dataset
5 6 2 3 4 4 3 -2 1 4 1 1 5 -3 2 4 -2 5 4 1
Sample Output
0 x -4 -2 -3