Longest Path in A DAG
Longest Path in A DAG
Suppose that we are given a directed acyclic graph = (, ) with real-valued edge
weights and two distinguished vertices and . Describe a dynamic-programming
approach for finding a longest weighted simple path from to . What does the subproblem
graph look like? What is the efficiency of your algorithm?
Given a directed acyclic graph = (, ), we need to first topologically sort this graph , then
compute the longest path to the vertices one by one in the sorted order. Of course, the start node
comes the first, whose distance is initialized to be zero, and the last node is . At every
iteration, a vertex is picked to compute the longest path by comparing . + (, ) for
every vertex which is connected to through an edge (, ). That is, every iteration will be
responsible for a subproblem, which is to find the longest weighted simple path from upto the
current node . Once all the vertices have been calculated, the longest weighted simple path from
to is the . , or the maximum distance among all the vertices.
Time Complexity: Time complexity of topological sorting is O(V+E). After finding topological
order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent
vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times.
Therefore, overall time complexity of this algorithm is O(V+E).