Given a weighted directed acyclic graph (DAG) and a source vertex, find the cost of the longest path from the source vertex to all other vertices present in the graph. If the vertex can’t be reached from the given source vertex, print its distance as infinity.

For example, consider the following DAG,

 
Longest path in DAG

The longest distance of source vertex 7 to every other vertex is:

dist(7, 0) =  7 (7 —> 3 —> 0)
dist(7, 1) = -1 (7 —> 1)
dist(7, 2) = -5 (7 —> 1 —> 2)
dist(7, 3) =  4 (7 —> 3)
dist(7, 4) =  9 (7 —> 3 —> 4)
dist(7, 5) = -4 (7 —> 5)
dist(7, 6) =  9 (7 —> 3 —> 0 —> 6)

Practice this problem

Prerequisite:

Find the cost of the shortest path in DAG using one pass of Bellman–Ford

 
We can easily solve this problem by following the above logic as well. The idea is to consider the edges’ negative weights and find the longest path from a given source in the graph. The cost of the longest path is just negative of its cost of the shortest path for any given vertex.

 
Here’s what Wikipedia has to say for Acyclic graphs:

The longest path between two given vertices s and t in a weighted graph G is the same thing as the shortest path in a graph -G derived from G by changing every weight to its negation. Therefore, if shortest paths can be found in -G, then longest paths can also be found in G. For most graphs, this transformation is not useful because it creates cycles of negative length in -G. But if G is a directed acyclic graph, then no negative cycles can be created, and the longest path in G can be found in linear time by applying a linear time algorithm for shortest paths in -G, which is also a directed acyclic graph.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
dist(7, 0) = 7
dist(7, 1) = -1
dist(7, 2) = -5
dist(7, 3) = 4
dist(7, 4) = 9
dist(7, 5) = -4
dist(7, 6) = 9
dist(7, 7) = 0

The time complexity of the above solution is O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.