图的问题

Given a directed weighted acyclic graph G = (V, E, W) and a vertex s, design an O(n+m) algorithm to find a longest path that starts from s, where n = |V|, m=|E|.  (Hint: Do topological sorting from s. (Only call DFS once.) Let v1 (= s), v2, v3, ...., vk, be the sorted sequence, k £ n. Define d(vi) to be the longest distance from s to vi. Initially, d(vi) = - ¥. Set d(v1) = 0.  When d(vi) have been computed, how to update d(v) for each v ÎAdj(vi)?)

 

Solution:

 

Longest-Path-for-DAG (G(V, E, W)

1.            Do topological sorting for G from s.

2.            Let v1 (= s), v2, v3, ...., vk, be the sorted sequence.

3.            for i ¬ 1 to k

4.              do {  d(vi) ¬ - ¥

5.                 p(vi) ¬ nil          //father pointer to its predecessor

6.                }

7.            d(v1) ¬ 0

8.            for i ¬ 1 to k-1

9.              do for each  v Î Adj(vi)

10.             if (d(vi) + w(vi, v)) > d(v)

11.                   then {    d(v) ¬ d(vi) + w(vi, v)

12.                           p(v) ¬ vi

13.                          }

14.        Let d(vi) = Max{ d(v1), d(v2), …, d(vk)}

15.        Stack S ¬ f                          //Clear a stack

16.        Push (S, vi)

17.        v ¬ Top(S)

18.        while  p(v) ¹ nil

19.          do {  Push (S, p(v))

20.            v ¬ p(v) }

21.        End    //The path is stored in the stack S from top to bottom.

 

Obviously, the time complexity is O(n+m).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值