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!
The problem has an optimal substructure. To find the longest path from vertex
cto vertexz, we first need to find the longest path fromcto all the predecessors ofz. Each problem of these is another smaller subproblem (longest path fromcto a specific predecessor).Lets denote the predecessors of
zasu1,u2,...,ukanddist[z]to be the longest path fromctozthendist[z]=max(dist[ui]+w(ui,z))..Here is an illustration with 3 predecessors omitting the edge set weights:
So to find the longest path to
zwe first need to find the longest path to its predecessors and take the maximum over (their values plus their edges weights toz).This requires whenever we visit a vertex
u, all ofu's predecessors must have been analyzed and computed.So the question is: for any vertex
u, how to make sure that once we setdist[u],dist[u]will never be changed later on? Put it in another way: how to make sure that we have considered all paths fromctoubefore considering any edge originating atu?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
vithen we have considered all paths leading toviand have the final value ofdist[vi].The time complexity: topological sort takes
O(V+E). In the worst case wherezis a leaf and all other vertices point to it, we will visit all the graph edges which givesO(V+E).