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).