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
c
to vertexz
, we first need to find the longest path fromc
to all the predecessors ofz
. Each problem of these is another smaller subproblem (longest path fromc
to a specific predecessor).Lets denote the predecessors of
z
asu1,u2,...,uk
anddist[z]
to be the longest path fromc
toz
thendist[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
z
we 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 fromc
tou
before 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
vi
then we have considered all paths leading tovi
and have the final value ofdist[vi]
.The time complexity: topological sort takes
O(V+E)
. In the worst case wherez
is a leaf and all other vertices point to it, we will visit all the graph edges which givesO(V+E)
.