Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum weighted path between two vertices in a directed acyclic Graph

Love some guidance on this problem:

G is a directed acyclic graph. You want to move from vertex c to vertex z. Some edges reduce your profit and some increase your profit. How do you get from c to z while maximizing your profit. What is the time complexity?

Thanks!

like image 368
evenodd Avatar asked Oct 20 '22 22:10

evenodd


1 Answers

The problem has an optimal substructure. To find the longest path from vertex c to vertex z, we first need to find the longest path from c to all the predecessors of z. Each problem of these is another smaller subproblem (longest path from c to a specific predecessor).

Lets denote the predecessors of z as u1,u2,...,uk and dist[z] to be the longest path from c to z then dist[z]=max(dist[ui]+w(ui,z))..

Here is an illustration with 3 predecessors omitting the edge set weights:

enter image description here

So to find the longest path to z we first need to find the longest path to its predecessors and take the maximum over (their values plus their edges weights to z).

This requires whenever we visit a vertex u, all of u's predecessors must have been analyzed and computed.

So the question is: for any vertex u, how to make sure that once we set dist[u], dist[u] will never be changed later on? Put it in another way: how to make sure that we have considered all paths from c to u before considering any edge originating at u?

Since the graph is acyclic, we can guarantee this condition by finding a topological sort over the graph. topological sort is like a chain of vertices where all edges point left to right. So if we are at vertex vi then we have considered all paths leading to vi and have the final value of dist[vi].

The time complexity: topological sort takes O(V+E). In the worst case where z is a leaf and all other vertices point to it, we will visit all the graph edges which gives O(V+E).

like image 187
Xline Avatar answered Oct 22 '22 20:10

Xline