Problem 435
Longest Path in a DAG
Medium · 20 pts · Graph, Topological Sort, Dynamic Programming
Problem
A directed acyclic graph has N nodes and weighted edges with positive weights. A path's length is the sum of its edge weights, and a path may start and end at any nodes (a single node is a path of length 0). Find the length of the longest path. In general graphs this is a hard problem, but in a DAG dynamic programming over a topological order solves it in O(N + M).
Input
First line: N and M. Next M lines: a directed edge u v w.
Output
Print the length of the longest path.
Constraints
1 <= N <= 100000; 0 <= M <= 200000; 1 <= w <= 10000; the graph has no cycles
Example input
3 3 1 2 3 2 3 4 1 3 5
Example output
7
Explanation
With edges 1→2 (3), 2→3 (4) and 1→3 (5), the path 1 → 2 → 3 has length 3 + 4 = 7, longer than the direct edge of length 5.