Maximum flow and minimum cut
Network flow is a powerful modeling tool: matching, disjoint paths, image segmentation, project selection and vulnerability cuts in code graphs reduce to it. Prove max-flow min-cut with augmenting paths, analyze Edmonds–Karp and Dinic, and introduce push–relabel. Half the lesson teaches modeling problems as flows.
After this lesson you can
- Prove max-flow min-cut and extract the cut from the residual graph.
- Implement Edmonds–Karp and Dinic and analyze their costs.
- Explain push–relabel and why it dominates in many practical applications.
- Model problems as maximum flow or minimum cut, including vertex capacities and demands.
- Relate maximum flow and minimum cut to linear-programming duality.
Before you start
Motivation: a network bottleneck
In October 1955, T. E. Harris and F. S. Ross delivered a secret RAND Corporation report to the United States Air Force on the capacity of the railway network connecting the Soviet Union with Eastern European countries. They reduced the map to 44 districts and 105 links, each with daily tonnage capacity, and calculated two things: the maximum that could travel between the endpoints (163 000 tons per day) and which links to cut to interrupt everything with least effort. The report’s diagram marks that set with a terse label: “the bottleneck.” Its total capacity was also 163 000 tons. The report was declassified in 1999 and Alexander Schrijver reconstructed its history in 2002.
The equality of those two figures is not accidental; it is this lesson’s central result. Lester Ford and Delbert Fulkerson, Harris’s RAND colleagues, proved it in 1956: in any network, the maximum transportable amount equals the capacity of the narrowest bottleneck. A flow-maximization problem and a problem of minimizing what must be cut are the same problem viewed from two sides.
What makes this theorem such a powerful tool is that many problems not about pipes reduce to it:
- Matching. Assigning workers to tasks, reviewers to papers or ads to slots is maximum flow on a bipartite graph; Hall’s theorem follows as a corollary (see the next lesson).
- Reliability. The number of independent paths connecting two servers, or nodes that must be lost to isolate them, is a maximum-flow problem (Menger’s theorem).
- Computer vision. Separating an object from its background while minimizing data disagreement and boundary length is an exact minimum cut in the pixel graph.
- Decisions with dependencies. Choosing projects when some require others (or modules to compile, or mines to excavate) is a minimum cut.
- Software security. The smallest set of functions in a call graph at which to place validation so no untrusted data reaches a sensitive operation without passing through it is a minimum vertex cut.
The lesson has two halves. The first proves max-flow min-cut using augmenting paths and analyzes three real algorithms: Edmonds–Karp, Dinic and push–relabel. The second teaches modeling: what transformations turn a problem into flow, why they work and where they fail. Finally, the theorem appears as a case of linear-programming strong duality.
Networks, flows and cuts
Two conventions simplify what follows. Set when . Assume the network has no antiparallel edges: if , then . This loses no generality because one edge can be split in two with an intermediate vertex without changing any flow. For brevity, if write , and likewise for .
The set of flows is a nonempty bounded polyhedron (zero flow belongs), and value is linear, so a maximum exists. The question is how to find it and, above all, how to certify a flow is maximum without comparing it with every other one. The certificate is a cut.
Proof
Sum conservation equations for all , each written as “outflow minus inflow ,” and add the definition of , which is “outflow minus inflow” at :
Consider each edge . If both endpoints lie in , it appears once with sign (leaving ) and once with sign (entering ), and cancels. If and , it appears only with . If and , only with . Edges with both endpoints in do not appear. What remains is . For the bound, by capacity and .
∎This states weak duality: any cut certifies an upper bound for any flow. If we find a flow and cut with , both are simultaneously optimal, as in optimization’s weak duality. The strong theorem says that such a pair always exists.
The residual graph and Ford–Fulkerson
A naive way to build a large flow is greedy: find an – path along unsaturated edges, send as much as possible and repeat. It fails. In the next figure’s network, path sends 2 units and saturates and ; no unsaturated-edge path remains, and flow stays at 2 when the maximum is 4. The mistake was using edge , and the greedy algorithm cannot undo it. Ford and Fulkerson allow undoing flow as another operation.
Augmenting along path with bottleneck means: for each arc of , if forward, ; if reverse, . The result remains a flow and has value . Capacities hold by definition of . Conservation also holds: each internal path vertex receives one arc of and sends another, and in all four cases (forward or reverse on either side) its balance stays unchanged; for example, if it enters by a forward arc and exits by a reverse one, it gains inflow on the first edge and loses inflow on the second. At the first arc increases outflow or reduces inflow, so value rises by .
The Ford–Fulkerson method is the obvious loop: start with ; while an augmenting path exists in , augment along it. Each iteration costs with a residual-graph traversal using adjacency lists (within a bound, and denote and as usual). It is a method rather than an algorithm because it does not specify path choice, and that choice determines everything else.
Termination with integer capacities. If every capacity is an integer, induction makes all intermediate flows and bottlenecks integers, so each augmentation increases value by at least 1. Since value is bounded by , the method terminates after at most augmentations in time . The bound depends on numeric values, not bit counts: it is pseudopolynomial, like knapsack. It is attained. In the figure’s ‘Trap’ network, with four edges of capacity and one central edge of capacity 1, an adversary always choosing the least-bottleneck path alternates direction through the central edge and needs unit augmentations. With , this is about four billion iterations for four vertices; BFS solves it in two.
Irrational capacities. With arbitrary real capacities the method may not terminate and, worse, its values may converge to a nonmaximum. Ford and Fulkerson gave an example in their 1962 book; Uri Zwick found the smallest possible ones in 1995. One has six vertices: three ‘internal’ edges of capacities , and , with satisfying , and all others of capacity . After an initial augmentation of 1, a cycle of four paths repeats with bottlenecks in round . Each round leaves residual capacities of the three internal edges in the same configuration scaled by , so the cycle repeats forever. Value converges to while maximum flow is . The cell executes it in exact arithmetic over , ruling out a rounding artifact.
from fractions import Fraction as Fr
import math
class Q5:
"""Números a + b·√5 con a, b racionales: aritmética exacta, sin redondeo."""
def __init__(self, a, b=0):
self.a, self.b = Fr(a), Fr(b)
def __add__(self, o): o = o if isinstance(o, Q5) else Q5(o); return Q5(self.a + o.a, self.b + o.b)
def __sub__(self, o): o = o if isinstance(o, Q5) else Q5(o); return Q5(self.a - o.a, self.b - o.b)
def signo(self):
a, b = self.a, self.b
if a >= 0 and b >= 0: return int(a > 0 or b > 0)
if a <= 0 and b <= 0: return -1
return (1 if a > 0 else -1) * (1 if a * a > 5 * b * b else -1)
def __lt__(self, o): return (self - o).signo() < 0
def __gt__(self, o): return (self - o).signo() > 0
def __float__(self): return float(self.a) + float(self.b) * math.sqrt(5)
r = Q5(Fr(-1, 2), Fr(1, 2)) # r = (√5 − 1)/2, que cumple r² = 1 − r
M = 2
V = ["s", "v1", "v2", "v3", "v4", "t"]
ix = {x: i for i, x in enumerate(V)}
aristas = [("s", "v1", M), ("s", "v2", M), ("s", "v4", M), ("v1", "t", M), ("v3", "t", M), ("v4", "t", M),
("v2", "v1", 1), ("v4", "v3", r), ("v2", "v3", 1)]
# residual: cap[(u, v)] para los arcos directos e inversos
cap = {}
for u, v, c in aristas:
cap[(ix[u], ix[v])] = c if isinstance(c, Q5) else Q5(c)
cap[(ix[v], ix[u])] = Q5(0)
def aumentar(camino):
arcos = [(ix[a], ix[b]) for a, b in zip(camino, camino[1:])]
assert all(cap[e] > Q5(0) for e in arcos), "el camino no es aumentante"
d = cap[arcos[0]]
for e in arcos[1:]:
if cap[e] < d: d = cap[e]
for (u, v) in arcos:
cap[(u, v)] = cap[(u, v)] - d
cap[(v, u)] = cap[(v, u)] + d
return d
p1 = ["s", "v4", "v3", "v2", "v1", "t"] # usa el arco inverso v3 -> v2
p2 = ["s", "v2", "v3", "v4", "t"] # usa el arco inverso v3 -> v4
p3 = ["s", "v1", "v2", "v3", "t"] # usa el arco inverso v1 -> v2
valor = aumentar(["s", "v2", "v3", "t"])
for ronda in range(1, 16):
deltas = [aumentar(p) for p in (p1, p2, p1, p3)]
for d in deltas:
valor = valor + d
if ronda <= 3 or ronda % 5 == 0:
print(f"ronda {ronda:2d}: cuellos ≈ {[f'{float(d):.2e}' for d in deltas]} valor ≈ {float(valor):.10f}")
print(f"límite 3 + 2r = {3 + 2 * float(r):.10f} flujo máximo 2M + 1 = {2 * M + 1}")Each round is legal (all four paths augment, as the assert checks) and none finishes the job. Edges of capacity never become saturated, so the method does not ‘see’ them until too late. Floating-point numbers cause a different but equally bad issue: bottlenecks become so small that rounding decides which arcs appear saturated. The remedy is not integer arithmetic but choosing paths well, as Edmonds–Karp does.
The max-flow min-cut theorem
Proof
(1) ⇒ (2). If an augmenting path existed, its bottleneck would be positive and augmenting would produce a flow of value .
(2) ⇒ (3). Let be vertices reachable from in and . By (2), , so is a cut. Take edge with and : if , forward arc would belong to and would be reachable; hence . Now take edge with and : if , reverse arc would belong to and again would be reachable; hence . By the cut lemma, .
(3) ⇒ (1). By the lemma, every flow satisfies .
∎The proof gives more than the theorem. First, a cut algorithm: when Ford–Fulkerson terminates, traversal from in the residual gives in time , and edges from to form a minimum cut. Second, existence of the maximum shows the theorem holds for real capacities even if Ford–Fulkerson with arbitrary paths does not find it. Third, the lesson’s most useful modeling result:
The proof is the termination argument: intermediate flows are integral and the last has no augmenting path, so it is maximum. Integrality lets us say “a flow of value with capacities 1” is equivalent to “ disjoint paths” or “a matching of size .” Without it, fractional maximum flow would say nothing about discrete objects.
Implementation from scratch
The standard representation stores edges in a flat array, with each forward edge at even index and its reverse at (XOR with 1 alternates between and ). Residual capacity lives in the array and forward-edge flow is its reverse’s residual capacity. Thus augmentation subtracts from and adds it to without distinguishing cases. Choose paths with BFS, defining Edmonds–Karp.
from collections import deque
class Red:
"""Red de flujo como lista de aristas: la arista e y su inversa e ^ 1 van emparejadas."""
def __init__(self, n):
self.n = n
self.ady = [[] for _ in range(n)] # ady[u] = índices de las aristas que salen de u
self.dst, self.cap = [], [] # destino y capacidad residual de cada arista
def arista(self, u, v, c):
self.ady[u].append(len(self.dst)); self.dst.append(v); self.cap.append(c)
self.ady[v].append(len(self.dst)); self.dst.append(u); self.cap.append(0)
return len(self.dst) - 2 # índice de la arista directa
def flujo(self, e): # flujo de la arista directa e = capacidad de su inversa
return self.cap[e ^ 1]
def camino_bfs(red, s, t):
"""Camino s-t más corto en el residual, como lista de aristas, o None."""
padre = [-1] * red.n
padre[s] = -2
cola = deque([s])
while cola:
u = cola.popleft()
for e in red.ady[u]:
v = red.dst[e]
if red.cap[e] > 0 and padre[v] == -1:
padre[v] = e
if v == t:
camino = []
while v != s:
camino.append(padre[v]); v = red.dst[padre[v] ^ 1]
return camino[::-1]
cola.append(v)
return None
def edmonds_karp(red, s, t):
valor, aumentos = 0, 0
while (camino := camino_bfs(red, s, t)) is not None:
delta = min(red.cap[e] for e in camino)
for e in camino:
red.cap[e] -= delta
red.cap[e ^ 1] += delta
valor += delta; aumentos += 1
return valor, aumentos
def corte_minimo(red, s):
"""S = vértices alcanzables desde s en el residual."""
S, pila = {s}, [s]
while pila:
u = pila.pop()
for e in red.ady[u]:
if red.cap[e] > 0 and red.dst[e] not in S:
S.add(red.dst[e]); pila.append(red.dst[e])
return S
# la red clásica de Cormen, Leiserson, Rivest y Stein
nombres = ["s", "v1", "v2", "v3", "v4", "t"]
idx = {x: i for i, x in enumerate(nombres)}
aristas = [("s", "v1", 16), ("s", "v2", 13), ("v2", "v1", 4), ("v1", "v3", 12), ("v3", "v2", 9),
("v2", "v4", 14), ("v4", "v3", 7), ("v3", "t", 20), ("v4", "t", 4)]
red = Red(len(nombres))
ids = [red.arista(idx[u], idx[v], c) for u, v, c in aristas]
valor, aumentos = edmonds_karp(red, idx["s"], idx["t"])
S = corte_minimo(red, idx["s"])
print(f"flujo máximo = {valor} en {aumentos} aumentos")
print("S =", sorted(nombres[i] for i in S))
cruzan = [(u, v, c) for (u, v, c) in aristas if idx[u] in S and idx[v] not in S]
print("aristas del corte:", cruzan, " capacidad =", sum(c for *_, c in cruzan))
print("flujo por arista:", {f"{u}->{v}": f"{red.flujo(e)}/{c}" for (u, v, c), e in zip(aristas, ids)})
# el diamante: aristas saturadas frente a aristas del corte
red = Red(4)
ids = [red.arista(u, v, 2) for u, v in [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]]
print("\ndiamante:", edmonds_karp(red, 0, 3), " S =", sorted(corte_minimo(red, 0)),
" aristas saturadas:", sum(red.flujo(e) == 2 for e in ids))The classic network’s maximum flow is 23, and the cut read from the residual is , with edges , and (). Edge crosses from to and, as the proof requires, carries zero flow. In the diamond, with four saturated edges for a two-edge cut.
Edmonds–Karp: shortest paths
Jack Edmonds and Richard Karp published it in 1972; Yefim Dinitz had reached the same idea (and something better, as we will see) in 1970 in the Soviet Union. The time bound does not depend on capacities and holds for real capacities. The key is a fact about distances. Let be distance, in arcs, from to in .
The proof is a minimal-counterexample argument you will reconstruct in the exercises. BFS distances satisfy triangle inequality for each arc , the same inequality guaranteeing shortest-path relaxation. Intuitively, augmenting along a shortest path only removes arcs that went up one level (saturated ones) and only adds reverse arcs that go down one level; neither creates shortcuts.
Proof
Call an arc on an augmenting path critical when its residual capacity is the bottleneck; each augmentation has at least one, and augmentation removes it from . Since the path is shortest, at that time. For to become critical again it must reappear in the residual, which occurs only if a later augmentation with flow uses arc ; then . By the previous theorem, , so
Between consecutive times is critical, distance to rises by at least 2. When is critical, lies on an augmenting path continuing to , so ; distance can only increase by 2 within that interval, and each arc is critical at most times. Possible residual arcs are the corresponding to each edge in both directions, and each augmentation has at least one critical arc: at most augmentations total. Each costs for BFS.
∎def camino_peor(red, s, t):
"""El camino simple s-t del residual con menor cuello (un adversario; solo para redes diminutas)."""
mejor, pila = None, []
def dfs(u, vistos):
nonlocal mejor
if u == t:
b = min(red.cap[e] for e in pila)
if mejor is None or b < mejor[0]:
mejor = (b, list(pila))
return
for e in red.ady[u]:
v = red.dst[e]
if red.cap[e] > 0 and v not in vistos:
pila.append(e); dfs(v, vistos | {v}); pila.pop()
dfs(s, {s})
return None if mejor is None else mejor[1]
def ford_fulkerson(red, s, t, elegir):
valor = aumentos = 0
while (camino := elegir(red, s, t)) is not None:
delta = min(red.cap[e] for e in camino)
for e in camino:
red.cap[e] -= delta; red.cap[e ^ 1] += delta
valor += delta; aumentos += 1
return valor, aumentos
def trampa(C):
red = Red(4)
for u, v, c in [(0, 1, C), (0, 2, C), (1, 2, 1), (1, 3, C), (2, 3, C)]:
red.arista(u, v, c)
return red
for C in [10, 100, 1000, 10000]:
print(f"C = {C:>6}: peor camino {ford_fulkerson(trampa(C), 0, 3, camino_peor)[1]:>6} aumentos,"
f" BFS {ford_fulkerson(trampa(C), 0, 3, camino_bfs)[1]} aumentos")The adversary’s augmentation count grows linearly with , hence exponentially with input bit length; with BFS it is constant. Another classic rule has a guarantee: choose the widest bottleneck path (the figure’s ‘Wide’ option), found with a Dijkstra variant. With integer capacities it makes augmentations: remaining flow is a residual maximum flow decomposable into at most paths (one per arc saturated during decomposition), so the widest takes at least fraction of it, and every augmentations the remainder drops by at least factor .
Dinic: blocking flows in phases
Edmonds–Karp wastes work: after every augmentation it runs a fresh BFS, even though the next shortest path often has the same length and distances have barely changed. Dinitz grouped all equal-length augmentations into a phase.
The Dinic algorithm (the Western spelling of Dinitz’s surname popularized by Shimon Even) repeats: calculate levels with BFS; if is unreachable, stop; otherwise find a blocking flow in and add it to .
A blocking flow need not be a maximum flow of : it is merely one that cannot be augmented without undoing anything, like the initial greedy algorithm’s result. It is weaker and therefore cheaper, yet suffices by the next lemma.
Proof
New arcs of reverse arcs of that carried flow, so they descend exactly one level. Other arcs of were already in and rise by at most one level (if they rose more, BFS would have assigned a smaller level). An – path in rises levels in total with steps of at most , so has at least arcs, with equality only if every arc rises one level, i.e. a path in using no new arc. But every path has an arc saturated by the blocking flow and absent from . Thus every path has at least arcs.
∎Since distance lies between 1 and , there are at most phases. We still need a fast blocking flow. The trick is a current-edge pointer per vertex: a DFS from always follows the pointed-to arc; on reaching , it augments and restarts at ; if stuck at vertex (no useful outgoing arc), it backtracks, marks dead for the rest of the phase and advances its predecessor’s pointer. A pointer advances only when discarding an arc that cannot help again this phase: it is saturated or leads to a dead vertex. Thus at most pointer advances occur per phase, and each augmentation follows at most arcs and saturates at least one. Phase cost is and total .
Dinic’s famous case is unit capacities. If every capacity is 1, blocking flow takes (each arc is saturated or discarded once), and there are phases. If the network is additionally unit in the sense that each vertex other than and has one incoming or one outgoing edge (as in bipartite matching), there are phases and total cost (Even and Tarjan, 1975). The argument is elegant: after phases distance is at least . Remaining flow decomposes in the residual into vertex-disjoint paths (by the unit condition), each of length at least , so at most remain. Each later phase increases flow by at least 1, so at most more phases remain. Applied to bipartite matching, this is the Hopcroft–Karp algorithm in the next lesson.
import random, time
def dinic(red, s, t, fases=None):
"""Flujo máximo de Dinic. Si se pasa una lista `fases`, anota (d(s, t), aumentos) de cada fase."""
n, ady, dst, cap = red.n, red.ady, red.dst, red.cap
valor = 0
while True:
nivel = [-1] * n # BFS de niveles en el residual
nivel[s] = 0
cola = deque([s])
while cola:
u = cola.popleft()
for e in ady[u]:
if cap[e] > 0 and nivel[dst[e]] < 0:
nivel[dst[e]] = nivel[u] + 1
cola.append(dst[e])
if nivel[t] < 0:
return valor
d_st, aumentos = nivel[t], 0
ptr = [0] * n # puntero de arista actual de cada vértice
while True: # flujo bloqueante: DFS iterativo por los punteros
pila, u = [], s
while u != t:
while ptr[u] < len(ady[u]):
e = ady[u][ptr[u]]
if cap[e] > 0 and nivel[dst[e]] == nivel[u] + 1:
break
ptr[u] += 1
if ptr[u] < len(ady[u]): # avanzar por la arista actual
e = ady[u][ptr[u]]
pila.append(e)
u = dst[e]
elif u == s: # s sin salida: el flujo ya es bloqueante
break
else: # callejón sin salida: retroceder
nivel[u] = -1 # u queda fuera del resto de la fase
u = dst[pila.pop() ^ 1]
ptr[u] += 1
if u != t:
break
delta = min(cap[e] for e in pila)
for e in pila:
cap[e] -= delta
cap[e ^ 1] += delta
valor += delta
aumentos += 1
if fases is not None:
fases.append((d_st, aumentos))
def construir(n, aristas):
red = Red(n)
for u, v, c in aristas:
red.arista(u, v, c)
return red
# la red de la figura: s = 0, a..d = 1..4 (arriba), e..h = 5..8 (abajo), t = 9
DINIC = [(0, 1, 7), (0, 5, 8), (4, 9, 9), (8, 9, 3), (0, 2, 3), (7, 9, 6), (1, 2, 1), (2, 3, 3), (3, 4, 5),
(5, 6, 4), (6, 7, 8), (7, 8, 8), (1, 5, 2), (6, 2, 6), (5, 2, 5), (2, 7, 6), (8, 3, 1)]
fases = []
print("red de la figura: flujo", dinic(construir(10, DINIC), 0, 9, fases), " fases (d(s,t), aumentos):", fases)
def rejilla(k, cmax, semilla):
"""Rejilla k x k con capacidades al azar; s alimenta la columna izquierda y t recoge la derecha."""
R = random.Random(semilla)
idv = lambda i, j: 2 + i * k + j
A = []
for i in range(k):
A += [(0, idv(i, 0), 10**6), (idv(i, k - 1), 1, 10**6)]
for j in range(k):
for a, b in [(i, j + 1), (i + 1, j), (i - 1, j), (i, j - 1)]:
if 0 <= a < k and 0 <= b < k:
A.append((idv(i, j), idv(a, b), R.randint(1, cmax)))
return 2 + k * k, A
for k in [10, 20]:
n, A = rejilla(k, 50, k)
t0 = time.perf_counter(); f_ek, caminos = edmonds_karp(construir(n, A), 0, 1); t_ek = time.perf_counter() - t0
fases = []
t0 = time.perf_counter(); f_d = dinic(construir(n, A), 0, 1, fases); t_d = time.perf_counter() - t0
print(f"rejilla {k}x{k} ({n} vértices, {len(A)} aristas): flujo {f_ek} = {f_d}")
print(f" Edmonds-Karp: {caminos} caminos y {caminos + 1} BFS ({1000 * t_ek:.0f} ms)")
print(f" Dinic: {sum(a for _, a in fases)} caminos en {len(fases)} fases, {len(fases) + 1} BFS ({1000 * t_d:.0f} ms)")
print(f" distancias por fase: {[d for d, _ in fases]}")The figure’s network reproduces the interactive’s four phases. On the grid, both algorithms augment along the same number of shortest paths (133), but Edmonds–Karp runs BFS per path and Dinic per phase (19 phases). Notice distances increase by one for a while and then jump: the lemma guarantees only that they increase.
Push–relabel: push excess downhill
All previous methods maintain a valid flow and improve it along complete – paths. Andrew Goldberg and Robert Tarjan (1986, published 1988) reversed the approach, following an idea of Alexander Karzanov (1974): start with something that is not a flow but has maximum possible value, and repair it using purely local operations.
The push–relabel algorithm starts by saturating all edges leaving , with and all other heights 0, and repeats one of two operations while an active vertex exists:
- Push: if a residual arc has , send along it. Water descends one level at a time.
- Relabel: if none exists, raise to , the lowest height permitting a push.
Both operations preserve validity of . The key to correctness is: with valid heights, no – residual path exists. A simple path has at most arcs and each descends at most one level, so cannot descend from to . When no active vertices remain, the preflow is a flow with no augmenting path and therefore maximum. Excess that does not fit in is not lost: relabeling raises stuck vertices above and water returns to through reverse arcs.
Cost. If is active, there is a residual path from to (excess came from and can return), and validity of gives . Thus each vertex is relabeled times: total. Saturating pushes are (between two saturations of one arc, both endpoints must rise two levels). Nonsaturating pushes are by a potential argument . Choosing the active vertex carefully improves the bound: FIFO gives and the highest-label rule .
Why it dominates in practice. Worst-case bounds do not explain it; two heuristics and locality do.
- Global relabeling. Occasionally recompute all heights as exact residual distance to (backward BFS). True heights guide water directly to instead of discovering the way through relabeling.
- Gap. If after relabeling no vertex remains at height , those between and can no longer reach (a residual path descends at most one level per arc and would pass through height ), so raise them at once to : their excess can only return to .
- Locality. Each operation touches one vertex and its arcs: no long paths are traversed, memory access is predictable and operations on distinct vertices are nearly independent, enabling parallelism.
Cherkassky and Goldberg’s classic 1997 experimental study established that highest-label push–relabel with global relabeling and gap is among the fastest methods on very different network families, and production libraries such as OR-Tools implement it. On computer-vision grids, a specialized augmenting-path method reusing search trees often wins instead (Boykov and Kolmogorov, 2004). Theory also advanced: in 2022, Chen, Kyng, Liu, Peng, Probst Gutenberg and Sachdeva published a almost-linear-time maximum-flow algorithm, , using interior-point methods and dynamic data structures (see the module frontier).
def push_relabel(red, s, t, hueco=True, alturas_exactas=True):
n, ady, dst, cap = red.n, red.ady, red.dst, red.cap
h, exceso, ptr = [0] * n, [0] * n, [0] * n
cuenta = {"empujes": 0, "saturantes": 0, "reetiquetados": 0, "huecos": 0}
if alturas_exactas: # BFS hacia atrás desde t por arcos con capacidad
d = [-1] * n; d[t] = 0; cola = deque([t])
while cola:
v = cola.popleft()
for e in ady[v]: # e = v -> u; el arco u -> v es e ^ 1
u = dst[e]
if cap[e ^ 1] > 0 and d[u] < 0:
d[u] = d[v] + 1; cola.append(u)
h = [x if x >= 0 else n for x in d]
h[s] = n
activos = deque()
for e in ady[s]: # preflujo: saturar las aristas de s
if cap[e] > 0:
v, c = dst[e], cap[e]
cap[e] -= c; cap[e ^ 1] += c
exceso[v] += c; exceso[s] -= c
if v != t and v not in activos:
activos.append(v)
while activos:
u = activos[0]
while exceso[u] > 0: # descargar u
if ptr[u] == len(ady[u]): # reetiquetar
vieja = h[u]
h[u] = 1 + min(h[dst[e]] for e in ady[u] if cap[e] > 0)
ptr[u] = 0
cuenta["reetiquetados"] += 1
if hueco and 0 < vieja < n and not any(h[v] == vieja for v in range(n) if v not in (s, t)):
elevados = [v for v in range(n) if v not in (s, t) and vieja < h[v] < n]
for v in elevados:
h[v] = n + 1; ptr[v] = 0
cuenta["huecos"] += bool(elevados)
continue
e = ady[u][ptr[u]]
v = dst[e]
if cap[e] > 0 and h[u] == h[v] + 1: # empujar cuesta abajo
delta = min(exceso[u], cap[e])
cap[e] -= delta; cap[e ^ 1] += delta
exceso[u] -= delta; exceso[v] += delta
cuenta["empujes"] += 1
if v not in (s, t) and v not in activos:
activos.append(v)
if cap[e] == 0:
cuenta["saturantes"] += 1
ptr[u] += 1
else:
ptr[u] += 1
activos.popleft()
return exceso[t], cuenta
CLRS = [(0, 1, 16), (0, 2, 13), (2, 1, 4), (1, 3, 12), (3, 2, 9), (2, 4, 14), (4, 3, 7), (3, 5, 20), (4, 5, 4)]
for hueco, exactas in [(False, False), (True, False), (True, True)]:
print(f"red clásica, hueco={hueco!s:5} alturas exactas={exactas!s:5}:", push_relabel(construir(6, CLRS), 0, 5, hueco, exactas))
def aleatoria(n, m, cmax, semilla):
R = random.Random(semilla)
ar = set()
while len(ar) < m:
u, v = R.randrange(n), R.randrange(n)
if u != v:
ar.add((u, v))
return [(u, v, R.randint(1, cmax)) for u, v in sorted(ar)]
A = aleatoria(400, 4000, 100, 400)
print("\nred aleatoria, 400 vértices y 4000 aristas; Dinic da", dinic(construir(400, A), 0, 399))
for hueco, exactas in [(False, False), (True, True)]:
print(f" hueco={hueco!s:5} alturas exactas={exactas!s:5}:", push_relabel(construir(400, A), 0, 399, hueco, exactas))Classic-network counters match the interactive. The random network shows a dramatic difference: without heuristics, excess that does not fit in (maximum flow, 539, is much less than what leaves when outgoing edges are saturated) climbs one level at a time to to return to the source, and the algorithm makes around two hundred thousand pushes. With exact heights and gap, a few hundred.
Model with flows and cuts
Solving maximum flow is of little use without recognizing one. Flow and cut modeling is a small repertoire of transformations that can be combined. They share a proof structure: a bijection (or at least value-preserving correspondence) between original solutions and flows or cuts in the constructed network, supported by integrality.
Basic transformations
- Multiple sources and sinks. Add supersource with edges and supersink with edges , of infinite capacity or each source’s supply and sink’s demand.
- Undirected edges. Edge of capacity becomes arcs and each of capacity . A maximum flow might use both, but canceling their minimum does not change value, so one exists using only one.
- Vertex capacities. If at most units can pass through , split into and joined by an edge of capacity : edges entering enter and outgoing edges leave . Everything traversing crosses that edge. This also converts an edge cut to a vertex cut: if original edges have infinite capacity, only split-vertex edges are finite.
Disjoint paths: Menger’s theorem
Proof
Assign capacity 1 to every edge. A set of edge-disjoint paths gives flow value . Conversely, integrality gives an integer maximum flow, with values 0 or 1. Starting at and following flow-1 edges, conservation guarantees reaching (if a cycle forms, remove its flow without changing value); remove path edges and repeat times. Thus maximum path count equals maximum flow. A minimum cut has capacity equal to its edge count, and removing those edges disconnects from ; conversely, if removing edges disconnects them, reachable set after removal gives a cut of capacity at most . Max-flow min-cut makes both counts equal. For the vertex version apply this to the split-vertex network (capacity 1 on each and infinity elsewhere); for undirected graphs use two arcs per edge.
∎Hall’s matching theorem (Hall’s marriage theorem) is a special case, as in the next lesson. For the global minimum cut of an undirected graph, with neither nor fixed (network edge connectivity), fix any and solve flows, one for each possible ; Karger’s randomized algorithm does it without flows.
Project selection and maximum-weight closure
There are projects; project has profit , possibly negative (a cost such as buying a machine), and requirements such as “choosing requires choosing .” Seek a closed set (if and requires , then ) maximizing . This is the maximum-weight closure of a directed graph (Picard, 1976), used in open-pit mining planning (removing a block requires removing those above it), deciding product features or packages to install.
Proof
If were not closed, there would be and with requiring , and infinite edge would cross from to . Conversely, for closed , cut crosses no infinite edge. Edges that do cross are with and , contributing lost profits, and with and , contributing paid costs. Thus .
∎The interpretation applies widely: source and sink edges encode the cost of each isolated decision, and infinite edges encode hard constraints. A finite-capacity cut is exactly a decision respecting the constraints.
Image segmentation
To separate an object from background, assign each pixel a label (background or object), minimizing an energy with two terms:
The data term measures how implausible the label is for pixel intensity (e.g. , with means estimated from user-marked regions). The smoothness term charges for each separated neighbor pair: weighted boundary length. Greig, Porteous and Seheult observed in 1989 that minimum cut minimizes this energy exactly: each pixel is a vertex, with edge of capacity (cut if ends in background) and another of capacity , and every neighbor pair is joined by two arcs of capacity . A cut is a labeling ( if ) and its capacity is exactly . User seeds are imposed with infinite capacity toward or .
The figure shows the tradeoff fixed by and two known model limitations. Shrinkage bias: the smoothness term charges boundary length, and the shortest boundary encloses only seeds, so with large thin or distant parts vanish abruptly when boundary savings exceed the entire region’s data cost. And dependence on the data term: if background has more than one intensity, two means do not describe it. In the gradient, contrast-dependent weights help: cutting is cheap at strong edges and expensive within smooth areas, so large no longer shrinks the object but sticks the boundary to its edges. Real systems (GrabCut, Rother, Kolmogorov and Blake, 2004) use color Gaussian mixtures reestimated in a loop with the cut and weights making strong edges cheap to cut; semantic segmentation networks have replaced these methods in most uses, but their data-plus-regularity logic remains.
Which energies can be minimized this way? Kolmogorov and Zabih (2004) answered for binary energies with pairwise terms: exactly when each pairwise term is submodular, . Attracting labels admit a cut; repelling labels are generally NP-hard.
Circulations with demands and lower bounds
Sometimes each vertex has demand (negative for supply, with ), every edge has lower bound , and the question is whether a feasible flow exists. Reduce to maximum flow in two steps. First send the lower bound: assign edge capacity and correct demands, and . Then add supersource with edges of capacity for supply vertices and supersink with edges of capacity for demand vertices. A feasible flow exists exactly when maximum flow from to saturates every edge of , and original flow is recovered by adding to each edge.
import networkx as nx
G = nx.petersen_graph() # 3-regular, 10 vértices, 15 aristas
s, t = 0, 7 # no adyacentes
# caminos disjuntos en aristas: cada arista no dirigida da dos arcos de capacidad 1
red = Red(G.number_of_nodes())
for u, v in G.edges():
red.arista(u, v, 1); red.arista(v, u, 1)
print("caminos disjuntos en aristas:", dinic(red, s, t))
# caminos disjuntos en vértices: v_in = 2v, v_out = 2v + 1, con capacidad 1 entre ellos
def desdoblar(G, s, t):
red = Red(2 * G.number_of_nodes())
INF = 10**9
for v in G.nodes():
red.arista(2 * v, 2 * v + 1, INF if v in (s, t) else 1)
for u, v in G.edges():
red.arista(2 * u + 1, 2 * v, INF); red.arista(2 * v + 1, 2 * u, INF)
return red
red = desdoblar(G, s, t)
k = dinic(red, 2 * s + 1, 2 * t)
S = corte_minimo(red, 2 * s + 1)
separador = sorted(v for v in G.nodes() if 2 * v in S and 2 * v + 1 not in S)
print("caminos disjuntos en vértices:", k, " separador mínimo:", separador)
print("networkx:", nx.node_connectivity(G, s, t), sorted(nx.minimum_node_cut(G, s, t)))
def circulacion(n, aristas, demanda):
"""aristas (u, v, inf, sup); demanda[v] > 0 si v consume. Devuelve un flujo factible o None."""
d = list(demanda)
red = Red(n + 2); S, T = n, n + 1
ids = []
for u, v, lo, hi in aristas: # enviar ya la cota inferior y corregir las demandas
ids.append(red.arista(u, v, hi - lo))
d[v] -= lo; d[u] += lo
necesario = 0
for v in range(n):
if d[v] < 0: red.arista(S, v, -d[v])
elif d[v] > 0: red.arista(v, T, d[v]); necesario += d[v]
if dinic(red, S, T) < necesario:
return None
return [lo + red.flujo(e) for (u, v, lo, hi), e in zip(aristas, ids)]
# dos almacenes (0 y 1) ofrecen 3 y 4; dos tiendas (3 y 4) piden 5 y 2; el 2 es un nodo de tránsito.
# La ruta 0 -> 3 tiene que llevar al menos 2 unidades.
aristas = [(0, 2, 0, 3), (1, 2, 0, 4), (0, 3, 2, 3), (2, 3, 0, 4), (2, 4, 0, 2), (1, 4, 0, 1)]
print("\ncirculación:", circulacion(5, aristas, [-3, -4, 0, 5, 2]))
print("si la tienda 4 pidiera 4 y la 3 solo 3:", circulacion(5, aristas, [-3, -4, 0, 3, 4]))The two minimum separators differ (neighbors of and of ) but both have size 3, as required in a 3-regular graph with connectivity 3. The second circulation is impossible and flow detects it: store 4 receives edges of total capacity only .
Sanitization points in a call graph
In static security analysis, a data-flow analyzer marks sources (functions receiving untrusted data, such as request handlers or uploaded-file readers) and sinks (functions where unvalidated data is dangerous, such as executing a query, writing to disk or generating HTML). The defensive question is where to place validations or sanitization so every source-to-sink path passes through at least one while touching as few functions as possible. This is a minimum vertex cut: split each function with capacity equal to its validation cost, give calls infinite capacity, and connect a supersource to entries and sinks to a supersink.
import itertools
from collections import defaultdict
def grafo_de_llamadas(semilla=1):
"""Grafo de llamadas sintético por capas: entradas -> analizadores -> servicios -> acceso a datos -> sumideros."""
R = random.Random(semilla)
capas = {
"entrada": [f"handler_{x}" for x in ("login", "search", "upload", "comment", "export", "webhook", "admin", "api_v1")],
"analisis": [f"parse_{x}" for x in ("form", "json", "multipart", "query", "xml")],
"servicio": [f"svc_{x}" for x in ("user", "catalog", "files", "social", "report", "billing", "audit")],
"datos": ["repo_sql", "storage", "template"],
"sumidero": ["db_execute", "db_raw", "fs_write", "fs_delete", "render_html", "render_email", "shell_tool", "http_fetch"],
}
orden = list(capas)
llamadas = set()
for a, b in zip(orden, orden[1:]):
for f in capas[a]:
for g in R.sample(capas[b], R.randint(1, 3)):
llamadas.add((f, g))
# atajos que saltan capas: los que suelen pasarse por alto al revisar
llamadas |= {("handler_webhook", "svc_files"), ("parse_xml", "fs_write"), ("handler_admin", "shell_tool"),
("svc_report", "render_email"), ("parse_query", "repo_sql"), ("svc_billing", "http_fetch")}
return capas, sorted(llamadas)
capas, llamadas = grafo_de_llamadas()
funciones = [f for c in capas.values() for f in c]
idf = {f: i for i, f in enumerate(funciones)}
entradas, sumideros = capas["entrada"], capas["sumidero"]
print(f"{len(funciones)} funciones, {len(llamadas)} llamadas, {len(entradas)} entradas, {len(sumideros)} sumideros")
def corte_de_vertices(llamadas, coste):
"""Conjunto de coste mínimo de funciones que corta todo camino entrada -> sumidero."""
n = len(funciones)
red = Red(2 * n + 2)
S, T, INF = 2 * n, 2 * n + 1, 10**9
for f in funciones: # f_in = 2i, f_out = 2i + 1, con capacidad = coste de validar en f
red.arista(2 * idf[f], 2 * idf[f] + 1, coste(f))
for f, g in llamadas:
red.arista(2 * idf[f] + 1, 2 * idf[g], INF)
for f in entradas:
red.arista(S, 2 * idf[f], INF)
for f in sumideros:
red.arista(2 * idf[f] + 1, T, INF)
valor = dinic(red, S, T)
alc = corte_minimo(red, S)
return valor, [f for f in funciones if 2 * idf[f] in alc and 2 * idf[f] + 1 not in alc]
def quedan_caminos(validadas):
"""¿Queda algún camino entrada -> sumidero que no pase por una función validada?"""
ady = defaultdict(list)
for f, g in llamadas:
ady[f].append(g)
vistos = set(f for f in entradas if f not in validadas)
pila = list(vistos)
while pila:
f = pila.pop()
if f in sumideros:
return True
for g in ady[f]:
if g not in validadas and g not in vistos:
vistos.add(g); pila.append(g)
return False
valor, elegidas = corte_de_vertices(llamadas, lambda f: 1)
print("corte mínimo:", valor, "funciones:", elegidas, " ¿quedan caminos?", quedan_caminos(set(elegidas)))
print("validar todas las entradas:", len(entradas), " todos los sumideros:", len(sumideros))
# heurística voraz: validar la función que elimina más caminos entrada -> sumidero (el grafo es acíclico)
ady = defaultdict(list)
for f, g in llamadas:
ady[f].append(g)
def cuenta_caminos(validadas):
memo = {}
def desde(f):
if f in validadas: return 0
if f not in memo:
memo[f] = (1 if f in sumideros else 0) + sum(desde(g) for g in ady[f])
return memo[f]
return sum(desde(f) for f in entradas)
validadas = set()
while cuenta_caminos(validadas) > 0:
validadas.add(min((f for f in funciones if f not in validadas), key=lambda f: cuenta_caminos(validadas | {f})))
print("voraz por caminos eliminados:", len(validadas), sorted(validadas))
# certificado por fuerza bruta: ningún conjunto más pequeño corta todos los caminos
k = valor - 1
print(f"¿algún conjunto de {k} funciones corta todos los caminos?",
any(not quedan_caminos(set(c)) for c in itertools.combinations(funciones, k)))
# con costes: tocar entradas o sumideros (código generado, librerías ajenas) cuesta 5; el resto, 1
print("con costes:", corte_de_vertices(llamadas, lambda f: 5 if f in sumideros or f in entradas else 1))The minimum cut needs 5 functions; validating all entries or all sinks needs 8, and the greedy heuristic eliminating the most paths at each step needs 7. Brute force certifies no solution with 4 exists. With costs penalizing changes to entries and sinks, the cut shifts toward the parsing layer: four of five parsers, the service a webhook calls bypassing parsing, and the admin handler calling a sink directly. Those two shortcuts are exactly what a layer-based review would miss. The same technique quantifies how many checkpoints separate sources from sinks in real data-flow analysis; a small cut identifies where to focus review. It is a model, not a guarantee: sanitization protects only if correct for the particular sink (HTML escaping does not protect a SQL query), and a vertex cut assumes the validated function filters everything passing through it.
View as linear programming
Maximum flow is a linear program. With incidence matrix ( if edge leaves , if it enters, 0 otherwise), flow vector and the row of :
Its dual has variable for each bound and potential per vertex; removing redundancies gives
A cut gives a dual solution with and of value . The dual is a continuous relaxation of minimum cut: potentials can take intermediate values. Integrality of its optimum is not obvious; it follows because is totally unimodular: every square minor is , 0 or 1 (each column has one and one , and induction on minor size proves it). With such a matrix and integer data, all vertices of primal and dual polyhedra are integral. Max-flow min-cut is then linear-programming strong duality in a case where optima are also combinatorial. In this view, the augmenting-path proof is a primal–dual algorithm constructing flow and certificate together.
import numpy as np
from scipy.optimize import linprog
V, s, t = 6, 0, 5
E = CLRS
m = len(E)
B = np.zeros((V, m)) # incidencia: +1 donde sale la arista, -1 donde entra
for j, (u, v, c) in enumerate(E):
B[u, j], B[v, j] = 1, -1
cap = np.array([c for *_, c in E], dtype=float)
interior = [v for v in range(V) if v not in (s, t)]
primal = linprog(-B[s], A_eq=B[interior], b_eq=np.zeros(len(interior)), bounds=list(zip([0] * m, cap)), method="highs")
print("primal: flujo máximo =", -primal.fun)
# dual: min sum c_e d_e s.a. d_uv - p_u + p_v >= 0, p_s - p_t >= 1, d >= 0
nvar = m + V
A_ub, b_ub = [], []
for j, (u, v, _) in enumerate(E):
fila = np.zeros(nvar); fila[j] = -1; fila[m + u] = 1; fila[m + v] = -1
A_ub.append(fila); b_ub.append(0)
fila = np.zeros(nvar); fila[m + s] = -1; fila[m + t] = 1
A_ub.append(fila); b_ub.append(-1)
dual = linprog(np.concatenate([cap, np.zeros(V)]), A_ub=np.array(A_ub), b_ub=b_ub,
bounds=[(0, None)] * m + [(0, 1)] * V, method="highs-ds")
print("dual: capacidad =", dual.fun)
print(" d =", np.round(dual.x[:m], 6) + 0.0, " (1 en las aristas del corte)")
print(" p =", np.round(dual.x[m:], 6) + 0.0, " (1 en el lado S)")
R = np.random.default_rng(0)
dets = set()
for _ in range(3000):
k = R.integers(1, 6)
filas, cols = R.choice(V, k, replace=False), R.choice(m, k, replace=False)
dets.add(int(round(np.linalg.det(B[np.ix_(filas, cols)]))))
print("determinantes de 3000 submatrices cuadradas al azar de B:", sorted(dets))Dual simplex returns a vertex of the dual polyhedron, the cut found by Edmonds–Karp. The connection also explains what follows: minimum-cost flow in the next lesson is another linear program with the same matrix, while spectral clustering’s cut objectives relax combinatorial cuts (normalized, multipart) which, unlike – cut, are NP-hard.
The professional version
| Tool | Algorithm | When to use |
|---|---|---|
networkx.maximum_flow, minimum_cut | preflow (push–relabel) by default; also Edmonds–Karp, Dinitz, Boykov–Kolmogorov | prototypes, graphs with thousands of vertices, arbitrary attributes |
scipy.sparse.csgraph.maximum_flow | Edmonds–Karp or Dinic, in C on CSR | integer capacities, large sparse graphs |
OR-Tools SimpleMaxFlow | push–relabel with heuristics | production, millions of edges |
| Boost Graph Library, LEMON | push–relabel, Boykov–Kolmogorov | C++ |
| PyMaxflow | Boykov–Kolmogorov | computer-vision grids |
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_flow
def a_networkx(aristas):
G = nx.DiGraph()
for u, v, c in aristas:
G.add_edge(u, v, capacity=c)
return G
valor, flujo = nx.maximum_flow(a_networkx(CLRS), 0, 5)
corte, (S, T) = nx.minimum_cut(a_networkx(CLRS), 0, 5)
print("networkx:", valor, corte, sorted(S))
u, v, c = map(list, zip(*CLRS))
M = csr_matrix((np.array(c, dtype=np.int32), (u, v)), shape=(6, 6))
for metodo in ("edmonds_karp", "dinic"):
print("scipy", metodo, maximum_flow(M, 0, 5, method=metodo).flow_value)
discrepancias = 0
for semilla in range(40):
n = 30 + semilla
A = aleatoria(n, 6 * n, 50, semilla)
nuestro = dinic(construir(n, A), 0, n - 1)
discrepancias += nuestro != nx.maximum_flow_value(a_networkx(A), 0, n - 1)
u, v, c = map(list, zip(*A))
Msp = csr_matrix((np.array(c, dtype=np.int32), (u, v)), shape=(n, n))
discrepancias += nuestro != maximum_flow(Msp, 0, n - 1, method="dinic").flow_value
print("discrepancias con networkx y SciPy en 40 redes aleatorias:", discrepancias)scipy.sparse.csgraph.maximum_flow requires integer capacities in a CSR matrix and returns value and flow as a sparse matrix; for the cut traverse the residual manually, as above. networkx returns the cut directly with minimum_cut, and its minimum_node_cut function splits vertices for you.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How is (1) ⇒ (2) proved?
Step 1 of 4. What do you know about ?
seleccion_proyectos(beneficio, requiere). beneficio[i] is project i profit (an integer, possibly negative), and requiere is a list of pairs (i, j) meaning ‘choosing i requires choosing j’. Return (ganancia, elegidos): maximum total profit of a closed set and a set (set) attaining it. Use Red, dinic and corte_minimo from the lesson cells. Requirements may contain cycles.def seleccion_proyectos(beneficio, requiere):
"""Devuelve (ganancia máxima, conjunto cerrado de proyectos que la alcanza)."""
n = len(beneficio)
s, t = n, n + 1
red = Red(n + 2)
# tu código: aristas desde s, hacia t y de requisitos; flujo máximo; corte
return 0, set()Summary
- A flow respects capacities and conservation; a cut separates from . Net flow through any cut is , so every cut bounds every flow (weak duality).
- The residual graph adds reverse arcs allowing flow to be undone. Ford–Fulkerson augments along residual paths; with integer capacities it terminates in (pseudopolynomial), and with irrational capacities it may neither terminate nor converge to the maximum.
- Theorem: is maximum if and only if no augmenting path exists if and only if for some cut. Integer capacities admit an integer maximum flow (integrality).
- Edmonds–Karp (shortest paths) makes augmentations: . Dinic groups equal-length paths into phases using blocking flows and current-edge pointers: , and on unit networks such as bipartite matching.
- Push–relabel works with preflows and heights, pushing excess downhill: generic, with FIFO, and very fast in practice with global relabeling and gap.
- Modeling combines supersources, paired arcs, split vertices, infinite edges as hard constraints, and circulations for lower bounds. This gives Menger, project selection, binary image segmentation and vertex cuts in call graphs.
- As a linear program, maximum flow’s dual is minimum cut; total unimodularity of the incidence matrix makes optima integral, and the theorem is a case of strong duality.