Sub topic 12
Dynamic Programming on DAGs: Longest Paths
This chapter assumes you know Kahn's algorithm from earlier in the tutorial. It also assumes you can read Python dictionaries and lists, and that you know what a weighted edge is. The chapter shows how a topological order turns a hard problem, the longest path, into a single linear pass.
Why order matters for dynamic programming
Dynamic programming builds the answer for each node from answers already computed for other nodes. On a DAG, the longest path ending at node v depends only on the nodes with edges into v. A topological order places every one of those nodes before v. So if you process nodes in that order, each value is final before anything reads it.
In a general graph with cycles, finding the longest simple path is NP-hard. In a DAG it takes O(V + E) time: one topological sort plus one pass over every edge.
The recurrence
Let dist[v] be the length of the longest path that ends at v. Then:
dist[v] = 0ifvhas no incoming edges.- Otherwise,
dist[v] = max(dist[u] + w(u, v))over every edgeu -> v.
In practice you work forward through the edges. For each node u in topological order, you relax each outgoing edge, which means updating dist[v] whenever going through u gives a longer path. You also record the best predecessor of each node so that you can rebuild the path at the end.
Implementation
from collections import deque
def topo_order(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v, _ in graph[u]:
indegree[v] += 1
queue = deque(u for u, d in indegree.items() if d == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v, _ in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(graph):
raise ValueError("graph has a cycle")
return order
def longest_path(graph):
"""graph maps each node to a list of (successor, weight) pairs."""
order = topo_order(graph)
dist = {u: 0 for u in graph}
parent = {u: None for u in graph}
for u in order:
for v, w in graph[u]:
if dist[u] + w > dist[v]:
dist[v] = dist[u] + w
parent[v] = u
end = max(dist, key=dist.get)
path = []
node = end
while node is not None:
path.append(node)
node = parent[node]
path.reverse()
return dist[end], path
tasks = {
"fetch": [("compile", 3), ("lint", 1)],
"compile": [("test", 5)],
"lint": [("test", 1)],
"test": [("package", 2)],
"package": [],
}
print(longest_path(tasks))
# (10, ['fetch', 'compile', 'test', 'package'])In scheduling, this longest path is called the critical path. No schedule can finish faster than its length, even with unlimited workers, because every task on it must wait for the task before it.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Relaxing edges in dictionary or input order | A node's value is read before it is final, which gives answers that are too small | Always iterate over a topological order |
| Starting every `dist` at 0 when the path must begin at a given source | Paths that start at other nodes get counted | Set the source to 0 and all other nodes to `float("-inf")`, then skip nodes still at `-inf` |
| Running on a graph with a cycle | With positive weights, a path can loop forever and never stop growing | Let the topological sort raise on cycles, as `topo_order` does |
| Forgetting `parent` updates | You get the length but cannot rebuild the path | Update `parent[v]` on the same line that improves `dist[v]` |
Other DAG recurrences
The pattern stays the same and only the combining step changes. Some examples:
- Count the paths from a source:
count[v] += count[u]. - Find the earliest start time of each task: this is the longest-path value itself.
- Check whether a node is reachable from a source: propagate a boolean.
Exercise
Modify longest_path so it returns the longest path that starts at a given node source, not at any node. For tasks with source "lint", what should it return?
Show answer
Initialize dist[source] = 0 and every other node to float("-inf"). In the loop, skip any u whose dist[u] is still -inf. Then choose end only among nodes with a finite distance. For source "lint", the reachable distances are lint 0, test 1, and package 3, so the result is (3, ['lint', 'test', 'package']).
Exercise
Why does the algorithm run in O(V + E) time?
Show answer
The topological sort takes O(V + E). The DP loop visits each node once and relaxes each edge exactly once with O(1) work. Rebuilding the path takes O(V).