Paths in DAGs
Longest paths, critical paths and dynamic programming in topological order.
Longest paths are NP-hard in general graphs, and shortest paths with negative edges need Bellman–Ford's . In a DAG both take one linear pass: relax the edges in topological order. The same pass schedules projects, counts paths, and is exactly what every dynamic program does.
What you’ll learn
- Prove that relaxing edges in topological order computes single-source shortest and longest paths in a DAG in for any real weights, and explain why the longest simple path is NP-hard in general graphs.
- Compute earliest starts, latest finishes, slack and critical paths of a project network.
- Evaluate path counts and other path sums over a semiring in topological order, and handle the overflow that path counts cause.
- Compute transitive closures and reductions, minimum path covers through matching, and dominator trees, and know the landmark algorithms for each.
Relaxation in topological order
Fix a source in a DAG whose edges carry real weights , negative ones allowed. Start with and for every other vertex, then process the vertices in topological order, relaxing each edge that leaves the current vertex:
Never too small. By induction on the relaxations, every finite is the length of some path from to , so at all times
Exact in time. Let be a shortest path. Its edges point forward, so the loop processes in this order. By induction when is processed, and relaxing its edge to gives
Acyclicity does two jobs here: it makes shortest and longest paths well defined for any weights (there are finitely many paths and no cycle to go around), and it hands the algorithm an order in which every path's vertices appear. Dijkstra's algorithm has to discover such an order greedily, and that only works with non-negative weights.
Every dynamic program is a DAG. Make each subproblem a vertex, with an edge from every subproblem to each subproblem that uses it. Filling the table in a valid order is processing a topological order, and a minimizing recurrence is a shortest-path relaxation. The Optimal lesson DP as Shortest Paths in a DAG develops this view.
A directed graph with cycles has positive edge weights. You negate every weight and run Bellman–Ford from , hoping to obtain longest simple paths. What happens?
- It returns the longest simple paths in
- It works if you run Dijkstra's algorithm instead of Bellman–Ford
- Any cycle reachable from becomes a negative cycle, and Bellman–Ford reports it instead of distances
- It returns longest paths, but only for the vertices that lie on cycles
Show the answer
C. Any cycle reachable from becomes a negative cycle, and Bellman–Ford reports it instead of distances
Bellman–Ford computes shortest walks, which exist only when no negative cycle is reachable, and after negation every reachable positive cycle is one. The longest simple path is NP-hard, so no such simple trick can solve it unless P = NP.
Critical paths: scheduling a project
A project is a set of tasks with durations and precedence rules (" starts once and are done"), with as many workers as needed. Make each task a vertex of a DAG, weighted by its duration. Then:
- The earliest start is a longest-path length: the maximum of over the prerequisites of , or if there are none.
- The project length is the maximum of .
- The latest finish , computed backward in reverse topological order, is the minimum of over the tasks that require , or if there are none.
- The slack is how long can slip without delaying the project. The tasks with zero slack form the critical paths, the longest paths of the DAG.
Tasks, with durations in days: 3; 6; 4, after ; 2, after and ; 3, after and ; 2, after ; 4, after . With unlimited workers, what is the shortest possible project length?
Show the answer
13
The longest chain is : days. The chain takes and only , so they have slack.
from collections import deque
def critical_path(tasks):
"""tasks: {name: (duration, [prerequisites])} -> (length, earliest start, slack)."""
succ = {t: [] for t in tasks}
indeg = {t: len(pre) for t, (_, pre) in tasks.items()}
for t, (_, pre) in tasks.items():
for p in pre:
succ[p].append(t)
order, queue = [], deque(t for t in tasks if indeg[t] == 0)
while queue: # Kahn's algorithm
u = queue.popleft()
order.append(u)
for v in succ[u]:
indeg[v] -= 1
if indeg[v] == 0:
queue.append(v)
es = {} # forward pass: longest path into t
for t in order:
es[t] = max((es[p] + tasks[p][0] for p in tasks[t][1]), default=0)
length = max(es[t] + tasks[t][0] for t in tasks)
lf = {} # backward pass: latest finish
for t in reversed(order):
lf[t] = min((lf[q] - tasks[q][0] for q in succ[t]), default=length)
slack = {t: lf[t] - tasks[t][0] - es[t] for t in tasks}
return length, es, slackTwo linear passes after a topological sort: for tasks and precedence rules.
| Task | Duration | Requires | ES | LF | Slack |
|---|---|---|---|---|---|
| 3 | none | 0 | 4 | 1 | |
| 6 | none | 0 | 6 | 0 | |
| 4 | 3 | 8 | 1 | ||
| 2 | , | 6 | 8 | 0 | |
| 3 | , | 8 | 11 | 0 | |
| 2 | 11 | 13 | 0 | ||
| 4 | 3 | 13 | 6 |
To finish sooner you must shorten critical tasks: speeding up changes nothing, and when several critical paths exist, all of them must shrink. Choosing which tasks to speed up at least cost ("crashing" the project) is a linear program.
Counting paths and other path sums
The relaxation loop used nothing special about and . Replace them by any two operations that form a semiring: combines alternative paths, extends a path by one edge, and distributes over . Processing the vertices in topological order then computes, for every , the -sum over all paths from to of the -product of their edge values, with semiring operations. This is the algebraic path problem, and on a DAG it is always easy, because there are finitely many paths and no cycles to sum around.
| Question | (alternatives) | (along a path) | Edge value | Value at |
|---|---|---|---|---|
| Shortest path | ||||
| Longest path | ||||
| Number of paths | ||||
| Is reachable? | or | and | true | true |
| Widest path (largest bottleneck) | capacity |
To count the shortest paths from in a weighted DAG, keep and . When relaxing finds exactly, what should happen?
- Nothing, since does not change
Show the answer
D.
A tie means that every shortest path to , extended by , is another shortest path to , so their number is added. A strict improvement resets instead: and . This is the semiring of (distance, count) pairs.
Reachability structure: closure, covers and dominators
Transitive closure. Process the vertices in reverse topological order and set . Stored as bitsets of bits, each edge costs one OR of machine words: time and words of memory on a word RAM with -bit words. For graphs with cycles, first collapse each strongly connected component, whose vertices all reach the same set.
Transitive reduction. Aho, Garey and Ullman (1972) showed that a DAG has a unique smallest graph with the same reachability: keep exactly when no other path leads from to . In , , , , , the edge is implied and is dropped. They also showed that the reduction costs the same as the closure, up to constant factors. With cycles, the smallest subgraph with the same reachability is NP-hard to find: a strongly connected graph has one with edges exactly when it has a Hamiltonian cycle.
Minimum path cover. To cover every vertex with as few vertex-disjoint paths as possible, split each vertex into and , and join to for every edge . A matching in this bipartite graph links paths end to start, each matched edge merging two paths into one, so the minimum number of paths is minus the size of a maximum matching. If the paths may share vertices, run the same construction on the transitive closure: this is Fulkerson's (1956) constructive proof of Dilworth's theorem (1950), which says that the fewest chains covering a partial order equal the size of its largest antichain.
For general flow graphs, with cycles, Lengauer and Tarjan (1979) compute dominators in with a simple version and with a sophisticated one, where is the inverse Ackermann function; Alstrup, Harel, Lauridsen and Thorup (1999) reached linear time.
In the DAG with edges , , , and , which vertices other than lie on every path from to ?
- Only
- Only
- and
- , , and
Show the answer
C. and
is the lowest common ancestor of and , which is ; and is the only predecessor of , so . The dominators of are therefore , and itself. Neither nor is on every path: each one can be bypassed through the other.
Key takeaways
- In a DAG, relaxing edges in topological order gives single-source shortest or longest paths in for any real weights; in general graphs the longest simple path is NP-hard.
- The critical path method runs a forward pass of longest paths for earliest starts and a backward pass for latest finishes; slack is , and the zero-slack tasks form the critical paths.
- The same loop computes any path sum over a semiring, such as path counts, reachability or widest paths; counts grow exponentially, so use modular, big-integer or saturating arithmetic.
- Bitset closure costs ; a DAG's transitive reduction is unique (Aho, Garey & Ullman, 1972); a minimum path cover has minus a maximum matching paths; dominators of a DAG are LCAs of predecessors, and Lengauer–Tarjan handles general graphs.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does relaxing edges in topological order give correct shortest paths in a DAG with negative weights, where Dijkstra's algorithm can fail?
- Because a DAG cannot contain negative edges in the first place
- Because each vertex is processed only after every edge into it has been relaxed, so its distance is already final
- Because topological order processes vertices by increasing distance
- Because each vertex is relaxed times, as in Bellman–Ford
Show the answer
B. Because each vertex is processed only after every edge into it has been relaxed, so its distance is already final
Every path's vertices appear in topological order, so all edges into are relaxed before is used, whatever their signs. Dijkstra's algorithm instead assumes that the smallest tentative distance is final, which a later negative edge can contradict.
In the example project, task (slack 6 days) is delayed by 4 days. What happens to the project length of 13 days?
- It grows to 17 days
- It grows to 15 days
- It stays at 13 days
- It grows to 14 days
Show the answer
C. It stays at 13 days
Slack is exactly how long a task can slip without moving the end date. A 4-day delay uses 4 of 's 6 days, so now ends on day 11, still before 13. A 7-day delay would push the project to 14 days.
A DAG has 10 vertices, and a maximum matching in its split bipartite graph (an edge for each edge ) has 7 edges. What is the minimum number of vertex-disjoint paths that cover every vertex?
- 3
- 7
- 10
- 17
Show the answer
A. 3
Start with 10 one-vertex paths; each matched edge links the end of one path to the start of another, merging two paths into one. With 7 merges, paths remain, and a smaller cover would give a larger matching.
You compute the transitive closure of a DAG with vertices and edges, using bitsets of 64-bit words in reverse topological order. About how many word operations does it take?
- About
- About
- About
- About
Show the answer
A. About
Each edge ORs one bitset of words into another: word operations, a fraction of a second. The memory, bits MB, is the real limit.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §22.2 on shortest paths in DAGs.
- J. E. Kelley & M. R. Walker, "Critical-path planning and scheduling," Proceedings of the Eastern Joint Computer Conference (1959).
- A. V. Aho, M. R. Garey & J. D. Ullman, "The transitive reduction of a directed graph," SIAM Journal on Computing 1(2) (1972), 131–137.
- T. Lengauer & R. E. Tarjan, "A fast algorithm for finding dominators in a flowgraph," ACM Transactions on Programming Languages and Systems 1(1) (1979), 121–141.
- S. Alstrup, D. Harel, P. W. Lauridsen & M. Thorup, "Dominators in linear time," SIAM Journal on Computing 28(6) (1999), 2117–2132.