Sub topic 10
Implementing Edmonds-Karp with Paired Edges
This chapter assumes you know the Edmonds-Karp loop from the previous chapter: run a BFS on the residual graph, find the bottleneck, push flow, and repeat. It also assumes you can read adjacency lists and Python classes.
Why Move Away from the Matrix
The adjacency-matrix version is short, but each BFS scans every row in full. That costs O(V²) per search, even when the graph is sparse. A matrix also holds only one number per ordered pair (u, v), so parallel edges have to be merged into a single capacity before you start.
An adjacency list lets one BFS run in O(V + E). The hard part is the reverse edge. When you push flow along u → v, you must raise the residual capacity of v → u, and you need to reach that reverse edge in O(1) time.
The Paired-Edge Trick
Store all edges in flat arrays, to and cap. Every time you add an edge, append the forward edge and then its reverse right after it. The forward edge gets an even index e. The reverse edge gets e + 1. For any index, e ^ 1 (bitwise XOR with 1) flips between the two: 4 ^ 1 = 5 and 5 ^ 1 = 4.
The reverse edge's to field holds u, so to[e ^ 1] gives the tail of edge e. The path walk uses this to step backward from the sink without a separate parent-node array.
The Implementation
from collections import deque
class MaxFlow:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)] # edge indices leaving each node
self.to = []
self.cap = []
def add_edge(self, u, v, c):
self.graph[u].append(len(self.to))
self.to.append(v)
self.cap.append(c)
self.graph[v].append(len(self.to))
self.to.append(u)
self.cap.append(0)
def max_flow(self, s, t):
flow = 0
while True:
parent_edge = [-1] * self.n
visited = [False] * self.n
visited[s] = True
queue = deque([s])
while queue and not visited[t]:
u = queue.popleft()
for e in self.graph[u]:
v = self.to[e]
if not visited[v] and self.cap[e] > 0:
visited[v] = True
parent_edge[v] = e
queue.append(v)
if not visited[t]:
return flow
bottleneck = float('inf')
v = t
while v != s:
e = parent_edge[v]
bottleneck = min(bottleneck, self.cap[e])
v = self.to[e ^ 1]
v = t
while v != s:
e = parent_edge[v]
self.cap[e] -= bottleneck
self.cap[e ^ 1] += bottleneck
v = self.to[e ^ 1]
flow += bottleneck
mf = MaxFlow(6)
for u, v, c in [(0, 1, 16), (0, 2, 13), (1, 3, 12), (2, 1, 4),
(2, 4, 14), (3, 2, 9), (3, 5, 20), (4, 3, 7), (4, 5, 4)]:
mf.add_edge(u, v, c)
print(mf.max_flow(0, 5)) # 23The cap array stores residual capacity directly. To read the flow on an original edge e (an even index), compute cap[e ^ 1], because the reverse edge started at 0 and gains exactly the flow that was pushed forward.
Common Errors
| Mistake | Symptom |
|---|---|
| Adding the reverse edge only when it is "needed" | `e ^ 1` points at an unrelated edge, which corrupts the flow |
| Walking back with `parent[v]` nodes but updating the wrong edge | Parallel edges get mixed up, and the answer is too high or too low |
| Reusing a `MaxFlow` object for a second query | Residual capacities from the first run remain, so the second answer is wrong |
| Forgetting `self.cap[e ^ 1] += bottleneck` | No undo is possible, and the result is a non-maximal flow |
Exercise
You call addedge(2, 7, 5) and then addedge(2, 7, 3) on a fresh MaxFlow. Which indices hold the two forward edges, what is to[e ^ 1] for each, and why would the matrix version treat this input differently?
Show answer
The forward edges sit at indices 0 and 2, and their reverses sit at 1 and 3. For both, to[e ^ 1] is 2, the tail. The list version keeps the two parallel edges separate. A matrix has one cell for (2, 7), so the capacities must be summed to 8 first, and a plain assignment would silently drop one edge.
Exercise
What is the cost of one BFS in this implementation compared with the matrix version, for a graph with V = 10,000 and E = 30,000?
Show answer
The list version costs O(V + E), about 40,000 steps (the reverse edges double E, but the order stays the same). The matrix version costs O(V²), about 100,000,000 steps per BFS.