Graph Theory37 sections · 1633 units
Open in Course

Longest Flight Route - Core Idea

DP on topological order

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. So you can compute dist[v] = max(dist[u] + 1) for all predecessors uu.

This is dynamic programming. The state is dist[v] (longest path from source to vv). The transition is dist[v] = max(dist[v], dist[u] + 1) for each edge uvu \to v. Topological order is what makes this work.