Sub topic 12
Dynamic Programming on DAGs: Longest Paths
This chapter assumes you can already produce a topological order with Kahn's algorithm or DFS, as covered in earlier chapters. It also assumes you know adjacency lists and Big-O notation. You will see that a topological order is a useful input in its own right. If you process the nodes in that order, many path problems become a single linear pass. The main example is the longest path, which is hard on general graphs and easy on DAGs.
Why Longest Path Is Special
On a general directed graph, finding the longest simple path is NP-hard. A path that visits every vertex is a Hamiltonian path, so a fast longest-path algorithm would also solve the Hamiltonian path problem. Cycles cause the difficulty. Once a cycle exists, a path could loop around it again and again, so you have to track which vertices you have already used. That tracking makes the state space blow up.
A DAG has no cycles, so every path is automatically simple. The problem then has optimal substructure: the longest path ending at v is the longest path ending at some predecessor u, plus the edge u -> v. That recurrence is well defined only if each dist[u] is computed before anyone reads it. A topological order guarantees this.
The Recurrence and the Order
Define dist[v] as the length of the longest path that ends at v. Then:
dist[v] = 0ifvhas no incoming edges.dist[v] = max(dist[u] + w(u, v))over every edgeu -> votherwise.
You can evaluate this in two equivalent styles:
- Pull: for each
vin order, look at its predecessors. This needs a reverse adjacency list. - Push (relaxation): for each
uin order, update every successorvwithdist[u] + w. This works directly on the usual successor list.
The push style is more common because the graph is already stored that way. Here is the unweighted version, where each edge has length 1:
def longest_path_lengths(graph, order):
"""order must be a topological order containing every node."""
dist = {u: 0 for u in order}
for u in order:
for v in graph.get(u, []):
dist[v] = max(dist[v], dist[u] + 1)
return dist
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": ["e"], "e": []}
order = ["a", "b", "c", "d", "e"]
print(longest_path_lengths(graph, order))
# {'a': 0, 'b': 1, 'c': 1, 'd': 2, 'e': 3}Why each value is final when it is used
Consider the moment the loop reaches u. Every edge x -> u has a tail x that comes before u in the topological order, so the loop has already processed x and relaxed x -> u. No later step can change dist[u], because later nodes never have edges back into u. Induction along the order gives the result: each node's value is final before it is pushed forward. Every edge is relaxed exactly once, so the pass costs O(V + E), and the topological sort itself costs O(V + E) as well.
Weighted Edges and Recovering the Path
Real problems usually have weights, and you usually want the path itself, not only its length. Store a parent pointer whenever a relaxation improves dist[v], then walk the pointers back from the best endpoint.
The example models a project. Edge weights are the time needed before the next milestone can start. The longest path is the critical path: the chain of work that sets the minimum project duration.
from collections import deque
def topo_order(graph):
"""graph maps u to a list of (v, weight) pairs."""
indegree = {u: 0 for u in graph}
for u in graph:
for v, _ in graph[u]:
indegree[v] = indegree.get(v, 0) + 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.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
return order
def critical_path(graph):
order = topo_order(graph)
dist = {u: 0 for u in order}
parent = {u: None for u in order}
for u in order:
for v, w in graph.get(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
project = {
"start": [("a", 3), ("b", 2)],
"a": [("c", 4)],
"b": [("c", 1), ("d", 5)],
"c": [("end", 2)],
"d": [("end", 1)],
"end": [],
}
print(critical_path(project))
# (9, ['start', 'a', 'c', 'end'])Trace it once by hand. Kahn's algorithm produces start, a, b, c, d, end. Relaxing from start sets a = 3 and b = 2. Relaxing from a sets c = 7. From b, the edge to c offers only 3, so c stays at 7, and d becomes 7. From c, end becomes 9. From d, end is offered 8 and keeps 9. The parent pointers lead from end back through c and a to start.
The strict > comparison keeps the first path found when there is a tie. Use >= if you prefer the last one. Both choices are correct, but pick one on purpose if your output must be deterministic.
Initialization Choices
Starting every node at 0 answers the question "what is the longest path ending here, starting anywhere?" Any node may act as a start. If instead you need paths from one specific source s, initialize dist[s] = 0 and every other node to negative infinity. Unreachable nodes then stay at negative infinity rather than incorrectly reporting 0.
| Question | Initial `dist` | Combine | Unreachable nodes |
|---|---|---|---|
| Longest path ending at v, any start | 0 everywhere | `max` | not applicable |
| Longest path from source s | 0 at s, `-inf` elsewhere | `max` | stay `-inf` |
| Shortest path from source s | 0 at s, `inf` elsewhere | `min` | stay `inf` |
| Number of paths from s | 1 at s, 0 elsewhere | `+=` | stay 0 |
The Same Pass Handles Shortest Paths with Negative Weights
Switch max to min and you get single-source shortest paths in O(V + E). The same correctness argument holds, so negative edge weights cause no problem. That beats Dijkstra, which cannot handle negative edges, and Bellman-Ford, which takes O(VE). A negative cycle would break shortest paths, but a DAG cannot contain any cycle.
import math
def dag_shortest_from(graph, order, source):
dist = {u: math.inf for u in order}
dist[source] = 0
for u in order:
if dist[u] == math.inf:
continue
for v, w in graph.get(u, []):
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
g = {"s": [("x", 2), ("y", 5)], "x": [("y", -4)], "y": [("z", 1)], "z": []}
print(dag_shortest_from(g, ["s", "x", "y", "z"], "s"))
# {'s': 0, 'x': 2, 'y': -2, 'z': -1}Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Relaxing in a non-topological order | Values too small, no error raised | Always compute the order first |
| Order missing isolated nodes | `KeyError` on lookup | Include every node in the in-degree map |
| Using 0 instead of `-inf` for single-source | Unreachable nodes report length 0 | Initialize with `-math.inf` |
| Forgetting `parent` updates on ties | Path inconsistent with `dist` | Update `parent` in the same branch as `dist` |
| Taking the answer from the last node in order | Misses a longer path ending elsewhere | Take `max` over all `dist` values |
| Skipping cycle detection | Meaningless output on cyclic input | Raise when the order is shorter than V |
Node Weights Instead of Edge Weights
Schedulers often attach durations to tasks (nodes) rather than to edges. You have two options. You can set dist[v] = duration[v] + max(dist[u]) over predecessors, initializing source nodes to their own duration. Or you can split each node into an "in" node and an "out" node joined by an edge carrying the duration. The first option is simpler. The second lets you reuse edge-weighted code unchanged.
Exercise
Using the project graph above, change the weight of edge b -> d from 5 to 6. What does critical_path(project) return now, and why?
Show answer
It returns (10, ['start', 'b', 'd', 'end']). The value d becomes 2 + 6 = 8, so end is offered 8 + 1 = 9 from d and 7 + 2 = 9 from c... wait, recheck: d = 8, end via d = 9, end via c = 9, a tie. Because relaxation uses strict >, c is processed before d and sets end = 9 first, so the result stays (9, ['start', 'a', 'c', 'end']). Raising b -> d to 7 instead gives d = 9 and end = 10 via d, returning (10, ['start', 'b', 'd', 'end']).
Exercise
Adapt the relaxation loop to count the number of distinct paths from "start" to "end" in the project graph. What count do you get?
Show answer
Initialize count["start"] = 1 and all others 0, then for each u in topological order and each successor v, do count[v] += count[u]. The counts are a = 1, b = 1, c = 2, d = 1, end = 3, so there are 3 paths: start-a-c-end, start-b-c-end, and start-b-d-end.
Exercise
A colleague runs longest_path_lengths(graph, sorted(graph)) on {"z": ["a"], "a": ["m"], "m": []}. What does it print, and what is the correct answer?
Show answer
The alphabetical order is a, m, z. Processing a sets m = 1, processing m does nothing, and processing z sets a = 1, but m is never updated again. It prints {'a': 1, 'm': 1, 'z': 0}. The correct topological order z, a, m gives {'z': 0, 'a': 1, 'm': 2}.