Graph Theory37 sections · 1633 units
Open in Course

Dynamic Programming on DAGs

The Real Power

Finding the longest path in a general graph is NP-hard. But in a DAG, you can do it in linear time using topological sort. Why? Because topological order guarantees that when you process node vv, you have already processed all nodes uu that can reach vv.

This is dynamic programming. The state is dist[v] (longest path from source to vv). The transition is dist[v] = max(dist[u] + 1) for each edge uvu \to v. Topological order ensures all predecessors are computed before the current node.

The same pattern works for many problems: shortest path, counting paths, maximum/minimum cost paths. The core insight is that DAGs have no cycles, so there's a natural order to process nodes. And that order is the topological sort.