Algorithmic Heights第35题:Shortest Paths in DAG

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年

给定:加权DAG,其边缘权重为 至  和 边列表格式的顶点。

返回:数组 哪里  是从顶点开始的最短路径的长度  到顶点  ()。如果 从以下位置无法到达  组 到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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值