Shortest Paths in a DAG and Critical Paths
Relaxation showed that the order of relaxations is everything: relax the edges of every shortest path from front to back, and one pass suffices. In a general graph we do not know such an order in advance, which is why Bellman-Ford repeats its pass times. In a directed acyclic graph we do: a topological order puts every path's edges front to back. The result is a single-source shortest-path algorithm that runs in time, allows negative weights, and, with one sign flipped, computes longest paths, which is what project planners call the critical path.
The algorithm
DAG-SHORTEST-PATHS(G, w, s)
1 topologically sort the vertices of G
2 INITIALIZE-SINGLE-SOURCE(G, s)
3 for each vertex u, taken in topological order
4 for each v in G.Adj[u]
5 RELAX(u, v, w)Correctness. Let be a shortest path to . Its vertices appear in topological order, so the edges are relaxed in this order. By the path-relaxation property, . Unreachable vertices keep . A DAG has no cycles, so there is no negative cycle to worry about, and negative edge weights are fine.
Running time. The topological sort is (by DFS or Kahn's algorithm), and every edge is relaxed exactly once: in total.
Another way to see it: this is Bellman-Ford with the edges listed in topological order of their tails. Then the first pass already gets everything right, and the second pass confirms that nothing changes. The animation runs Bellman-Ford on a DAG with its edges listed exactly that way.
from collections import deque
INF = float("inf")
edges = [("A", "B", 3), ("A", "C", 6), ("B", "C", -2), ("B", "D", 5), ("C", "D", 4), ("C", "E", 3),
("D", "F", -1), ("E", "F", 2), ("E", "G", 6), ("F", "G", 1)]
V = "ABCDEFG"
adj = {v: [] for v in V}
indeg = {v: 0 for v in V}
for u, v, w in edges:
adj[u].append((v, w)); indeg[v] += 1
order, q = [], deque(v for v in V if indeg[v] == 0) # Kahn's algorithm
while q:
u = q.popleft(); order.append(u)
for v, _ in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
print("topological order:", " ".join(order))
d = {v: INF for v in V}; pi = {v: None for v in V}
d["A"] = 0
relaxations = 0
for u in order:
for v, w in adj[u]:
relaxations += 1
if d[u] + w < d[v]:
print(f"relax {u}->{v}: {d[u]} + {w} = {d[u] + w} < {d[v]}")
d[v], pi[v] = d[u] + w, u
print("distances:", d)
print(f"{relaxations} relaxations for {len(edges)} edges")
def path(v):
return path(pi[v]) + [v] if pi[v] else [v]
print("shortest path to G:", " -> ".join(path("G")))topological order: A B C D E F G
relax A->B: 0 + 3 = 3 < inf
relax A->C: 0 + 6 = 6 < inf
relax B->C: 3 + -2 = 1 < 6
relax B->D: 3 + 5 = 8 < inf
relax C->D: 1 + 4 = 5 < 8
relax C->E: 1 + 3 = 4 < inf
relax D->F: 5 + -1 = 4 < inf
relax E->G: 4 + 6 = 10 < inf
relax F->G: 4 + 1 = 5 < 10
distances: {'A': 0, 'B': 3, 'C': 1, 'D': 5, 'E': 4, 'F': 4, 'G': 5}
10 relaxations for 10 edges
shortest path to G: A -> B -> C -> D -> F -> G
The successful relaxations are the same as in the first pass of the animation, and each of the 10 edges is relaxed exactly once. Bellman-Ford, by comparison, would relax all 10 edges in each of up to 6 passes.
In C++
The C++ version computes the topological order by DFS finishing times and then relaxes in that order.
#include <algorithm>
#include <climits>
#include <cstdio>
#include <functional>
#include <utility>
#include <vector>
int main() {
const int n = 7; // A..G
std::vector<std::vector<std::pair<int, int>>> adj(n);
auto add = [&](char u, char v, int w) { adj[u - 'A'].push_back({v - 'A', w}); };
add('A','B',3); add('A','C',6); add('B','C',-2); add('B','D',5); add('C','D',4);
add('C','E',3); add('D','F',-1); add('E','F',2); add('E','G',6); add('F','G',1);
std::vector<int> order;
std::vector<bool> seen(n, false);
std::function<void(int)> visit = [&](int u) {
seen[u] = true;
for (auto [v, w] : adj[u]) if (!seen[v]) visit(v);
order.push_back(u);
};
for (int u = 0; u < n; ++u) if (!seen[u]) visit(u);
std::reverse(order.begin(), order.end());
const long long INF = LLONG_MAX / 4;
std::vector<long long> d(n, INF);
d[0] = 0;
for (int u : order) {
if (d[u] == INF) continue;
for (auto [v, w] : adj[u]) d[v] = std::min(d[v], d[u] + w);
}
std::printf("order:");
for (int u : order) std::printf(" %c", 'A' + u);
std::printf("\n");
for (int v = 0; v < n; ++v) std::printf("d(%c) = %lld\n", 'A' + v, d[v]);
}order: A B C E D F G
d(A) = 0
d(B) = 3
d(C) = 1
d(D) = 5
d(E) = 4
d(F) = 4
d(G) = 5
The DFS order differs from Kahn's, but any topological order gives the same distances.
Longest paths
In a general graph, finding a longest simple path is NP-hard. In a DAG it is easy: negate every weight and find shortest paths, or equivalently replace "less than" by "greater than" in RELAX and initialize with . Both work because a DAG has no cycles, so there are no positive cycles to go around forever. The DP view of the same computation fills a table over the vertices in topological order.
Critical paths
A project consists of tasks with durations, and some tasks cannot start until others finish. With unlimited workers, how soon can the project end, and which tasks must not slip? Make each task a vertex, each dependency an edge, and give each edge the weight . Add a start vertex with an edge of weight 0 to every task without prerequisites and a finish vertex reached from every task without dependents. A longest path from start to finish is a critical path: its length is the shortest possible project duration, because the tasks along it must run one after another. This is the core of the PERT and critical-path methods used in project management.
For every task the computation also gives:
- earliest start : the longest path from start to (a forward pass in topological order);
- latest start : the project length minus the longest path from to finish (a backward pass in reverse topological order);
- slack : how long can be delayed without delaying the project. Tasks on a critical path have slack 0.
The project below launches a mobile app.
tasks = {"design": 3, "backend": 5, "frontend": 4, "api-docs": 2, "testing": 3,
"store-review": 2, "marketing": 4, "launch": 1}
after = {"design": ["backend", "frontend", "marketing"], "backend": ["api-docs", "testing"],
"frontend": ["testing"], "api-docs": ["launch"], "testing": ["store-review"],
"store-review": ["launch"], "marketing": ["launch"], "launch": []}
order, seen = [], set()
def visit(u):
seen.add(u)
for v in after[u]:
if v not in seen:
visit(v)
order.append(u)
for t in tasks:
if t not in seen:
visit(t)
order.reverse()
es = {t: 0 for t in tasks} # forward pass: longest path to each task
for u in order:
for v in after[u]:
es[v] = max(es[v], es[u] + tasks[u])
length = max(es[t] + tasks[t] for t in tasks)
ls = {t: length - tasks[t] for t in tasks} # backward pass
for u in reversed(order):
for v in after[u]:
ls[u] = min(ls[u], ls[v] - tasks[u])
print(f"project length: {length} days")
print(f"{'task':>13} {'dur':>4} {'ES':>3} {'LS':>3} {'slack':>6}")
for t in order:
print(f"{t:>13} {tasks[t]:>4} {es[t]:>3} {ls[t]:>3} {ls[t] - es[t]:>6}")
critical, t = ["design"], "design"
while after[t]:
t = next(v for v in after[t] if ls[v] == es[v] and es[v] == es[t] + tasks[t])
critical.append(t)
print("critical path:", " -> ".join(critical))project length: 14 days
task dur ES LS slack
design 3 0 0 0
marketing 4 3 9 6
frontend 4 3 4 1
backend 5 3 3 0
testing 3 8 8 0
store-review 2 11 11 0
api-docs 2 8 11 3
launch 1 13 13 0
critical path: design -> backend -> testing -> store-review -> launch
The project needs 14 days, set by the chain design, backend, testing, store review, launch. Frontend work has one day of slack, the API documentation three, and marketing six: those tasks can start late, or take longer, without moving the launch date. Shortening any task on the critical path shortens the project (until another path becomes critical); shortening anything else does not help at all.
Test yourself
What is the running time of DAG-SHORTEST-PATHS with adjacency lists?
Why may a DAG have negative edge weights in this algorithm?
- Negative weights are ignored
- A DAG has no cycles, so it has no negative cycles, and the path-relaxation argument needs nothing else
- Because the topological sort makes weights positive
- It may not
A task on a critical path has which slack?
- 0
- 1
- Its duration
- The project length
Why is finding a longest path easy in a DAG but NP-hard in general graphs?
- Because DAGs are small
- In a DAG every path is simple, and negating weights gives a shortest-path problem without negative cycles
- Because longest paths are unique in DAGs
- It is NP-hard in DAGs too