Module contents
Lesson 21 of 33Advanced 120 min

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 c(u,v)=0c(u, v) = 0 when (u,v)∉E(u, v) \notin E. Assume the network has no antiparallel edges: if (u,v)∈E(u, v) \in E, then (v,u)∉E(v, u) \notin E. This loses no generality because one edge can be split in two with an intermediate vertex without changing any flow. For brevity, if X,Y⊆VX, Y \subseteq V write f(X,Y)=∑u∈X,v∈Y,(u,v)∈Ef(u,v)f(X, Y) = \sum_{u \in X, v \in Y, (u, v) \in E} f(u, v), and likewise for c(X,Y)c(X, Y).

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 v∈S∖{s}v \in S \setminus \{s\}, each written as “outflow minus inflow =0= 0,” and add the definition of ∣f∣\abs{f}, which is “outflow minus inflow” at ss:

∣f∣=∑v∈S(∑(v,w)∈Ef(v,w)−∑(u,v)∈Ef(u,v)).\abs{f} = \sum_{v \in S} \Big( \sum_{(v, w) \in E} f(v, w) - \sum_{(u, v) \in E} f(u, v) \Big).

Consider each edge (x,y)(x, y). If both endpoints lie in SS, it appears once with sign ++ (leaving xx) and once with sign −- (entering yy), and cancels. If x∈Sx \in S and y∈Ty \in T, it appears only with ++. If x∈Tx \in T and y∈Sy \in S, only with −-. Edges with both endpoints in TT do not appear. What remains is ∣f∣=f(S,T)−f(T,S)\abs{f} = f(S, T) - f(T, S). For the bound, f(S,T)≤c(S,T)f(S, T) \le c(S, T) by capacity and f(T,S)≥0f(T, S) \ge 0.

∎

This states weak duality: any cut certifies an upper bound for any flow. If we find a flow and cut with ∣f∣=c(S,T)\abs{f} = c(S, T), 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 ss–tt path along unsaturated edges, send as much as possible and repeat. It fails. In the next figure’s network, path s→a→b→ts \to a \to b \to t sends 2 units and saturates s→as \to a and b→tb \to t; no unsaturated-edge path remains, and flow stays at 2 when the maximum is 4. The mistake was using edge a→ba \to b, and the greedy algorithm cannot undo it. Ford and Fulkerson allow undoing flow as another operation.

Augmenting ff along path PP with bottleneck δ\delta means: for each arc of PP, if forward, f(u,v)←f(u,v)+δf(u, v) \gets f(u, v) + \delta; if reverse, f(v,u)←f(v,u)−δf(v, u) \gets f(v, u) - \delta. The result remains a flow and has value ∣f∣+δ\abs{f} + \delta. Capacities hold by definition of δ\delta. Conservation also holds: each internal path vertex receives one arc of PP 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 δ\delta inflow on the first edge and loses δ\delta inflow on the second. At ss the first arc increases outflow or reduces inflow, so value rises by δ\delta.

InteractiveAugmenting paths and reverse edges
22222sabtlast: s→a→b→t (+2)
  • forward arc: c − f
  • reverse arc: f
  • augmenting path
Network
View
Path
Flow value ∣f∣\abs{f}2
Minimum cut capacity4
Augmentations made1
Proposed path bottleneck·
Build a path from ss to tt by selecting neighboring vertices along residual arcs (with dashed rings). Select a vertex on the path to truncate it.
Initial state: the diamond with 2 units already sent along greedy path s→a→b→ts \to a \to b \to t, in residual view. Aqua arcs are remaining capacity (c−fc - f); orange arcs are flow that can be returned (ff). Build a path by clicking vertices from ss: the only remaining one uses reverse arc b→ab \to a, and augmenting empties edge a→ba \to b. Switch to flow view to see it. At completion, vertices reachable from ss are shaded and cut edges marked red. Then try the ‘Classic’ network with ‘Worst’ (7 augmentations) and ‘BFS’ (3), and ‘Trap’ with ‘Worst’ and ‘To the end’: 40 augmentations where BFS needs 2. In flow view, click an edge to change its capacity.

The Ford–Fulkerson method is the obvious loop: start with f=0f = 0; while an augmenting path exists in GfG_f, augment along it. Each iteration costs O(E)\bigO(E) with a residual-graph traversal using adjacency lists (within a bound, VV and EE denote ∣V∣\abs{V} and ∣E∣\abs{E} 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 c({s},V∖{s})c(\{s\}, V \setminus \{s\}), the method terminates after at most ∣f∗∣\abs{f^*} augmentations in time O(E∣f∗∣)\bigO(E\abs{f^*}). 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 CC and one central edge of capacity 1, an adversary always choosing the least-bottleneck path alternates direction through the central edge and needs 2C2C unit augmentations. With C=231C = 2^{31}, 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 11, rr and 11, with r=(5−1)/2r = (\sqrt5 - 1)/2 satisfying r2=1−rr^2 = 1 - r, and all others of capacity M=2M = 2. After an initial augmentation of 1, a cycle of four paths repeats with bottlenecks r2k−1,r2k−1,r2k,r2kr^{2k-1}, r^{2k-1}, r^{2k}, r^{2k} in round kk. Each round leaves residual capacities of the three internal edges in the same configuration scaled by r2r^2, so the cycle repeats forever. Value converges to 1+2∑k≥1r2k−2=1+2/(1−r2)=3+2r≈4.2361 + 2\sum_{k \ge 1} r^{2k-2} = 1 + 2/(1 - r^2) = 3 + 2r \approx 4.236 while maximum flow is 2M+1=52M + 1 = 5. The cell executes it in exact arithmetic over Q(5)\Q(\sqrt5), ruling out a rounding artifact.

[ ]Nonterminating Ford–Fulkerson (Zwick, 1995)Browser
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 MM 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 δ\delta would be positive and augmenting would produce a flow of value ∣f∣+δ>∣f∣\abs{f} + \delta > \abs{f}.

(2) ⇒ (3). Let SS be vertices reachable from ss in GfG_f and T=V∖ST = V \setminus S. By (2), t∉St \notin S, so (S,T)(S, T) is a cut. Take edge (u,v)∈E(u, v) \in E with u∈Su \in S and v∈Tv \in T: if f(u,v)<c(u,v)f(u, v) < c(u, v), forward arc (u,v)(u, v) would belong to GfG_f and vv would be reachable; hence f(u,v)=c(u,v)f(u, v) = c(u, v). Now take edge (v,u)∈E(v, u) \in E with v∈Tv \in T and u∈Su \in S: if f(v,u)>0f(v, u) > 0, reverse arc (u,v)(u, v) would belong to GfG_f and again vv would be reachable; hence f(v,u)=0f(v, u) = 0. By the cut lemma, ∣f∣=f(S,T)−f(T,S)=c(S,T)−0\abs{f} = f(S, T) - f(T, S) = c(S, T) - 0.

(3) ⇒ (1). By the lemma, every flow gg satisfies ∣g∣≤c(S,T)=∣f∣\abs{g} \le c(S, T) = \abs{f}.

∎

The proof gives more than the theorem. First, a cut algorithm: when Ford–Fulkerson terminates, traversal from ss in the residual gives SS in time O(E)\bigO(E), and edges from SS to TT 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 kk with capacities 1” is equivalent to “kk disjoint paths” or “a matching of size kk.” 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 ee and its reverse at e⊕1e \oplus 1 (XOR with 1 alternates between 2k2k and 2k+12k + 1). Residual capacity lives in the array and forward-edge flow is its reverse’s residual capacity. Thus augmentation subtracts δ\delta from ee and adds it to e⊕1e \oplus 1 without distinguishing cases. Choose paths with BFS, defining Edmonds–Karp.

[ ]Edmonds–Karp from scratch and the residual cutBrowser
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 S={s,v1,v2,v4}S = \{s, v_1, v_2, v_4\}, with edges v1→v3v_1 \to v_3, v4→v3v_4 \to v_3 and v4→tv_4 \to t (12+7+4=2312 + 7 + 4 = 23). Edge v3→v2v_3 \to v_2 crosses from TT to SS and, as the proof requires, carries zero flow. In the diamond, S={s}S = \{s\} 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 δf(s,v)\delta_f(s, v) be distance, in arcs, from ss to vv in GfG_f.

The proof is a minimal-counterexample argument you will reconstruct in the exercises. BFS distances satisfy triangle inequality δ(s,v)≤δ(s,u)+1\delta(s, v) \le \delta(s, u) + 1 for each arc (u,v)(u, v), 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 (u,v)(u, v) on an augmenting path critical when its residual capacity is the bottleneck; each augmentation has at least one, and augmentation removes it from GfG_f. Since the path is shortest, δf(s,v)=δf(s,u)+1\delta_f(s, v) = \delta_f(s, u) + 1 at that time. For (u,v)(u, v) to become critical again it must reappear in the residual, which occurs only if a later augmentation with flow f′f' uses arc (v,u)(v, u); then δf′(s,u)=δf′(s,v)+1\delta_{f'}(s, u) = \delta_{f'}(s, v) + 1. By the previous theorem, δf′(s,v)≥δf(s,v)\delta_{f'}(s, v) \ge \delta_f(s, v), so

δf′(s,u)=δf′(s,v)+1≥δf(s,v)+1=δf(s,u)+2.\delta_{f'}(s, u) = \delta_{f'}(s, v) + 1 \ge \delta_f(s, v) + 1 = \delta_f(s, u) + 2.

Between consecutive times (u,v)(u, v) is critical, distance to uu rises by at least 2. When (u,v)(u, v) is critical, uu lies on an augmenting path continuing to tt, so 0≤δf(s,u)≤V−20 \le \delta_f(s, u) \le V - 2; distance can only increase by 2 within that interval, and each arc is critical at most V/2V/2 times. Possible residual arcs are the 2E2E corresponding to each edge in both directions, and each augmentation has at least one critical arc: at most 2E⋅V/2=VE2E \cdot V/2 = VE augmentations total. Each costs O(E)\bigO(E) for BFS.

∎
[ ]Augmentation counts: worst path versus BFSBrowser
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 CC, 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 O(Elog⁡∣f∗∣)\bigO(E \log \abs{f^*}) augmentations: remaining flow is a residual maximum flow decomposable into at most 2E2E paths (one per arc saturated during decomposition), so the widest takes at least fraction 1/(2E)1/(2E) of it, and every 2E2E augmentations the remainder drops by at least factor ee.

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 tt is unreachable, stop; otherwise find a blocking flow in LfL_f and add it to ff.

A blocking flow need not be a maximum flow of LfL_f: 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 Gf′G_{f'} reverse arcs of LfL_f that carried flow, so they descend exactly one level. Other arcs of Gf′G_{f'} were already in GfG_f and rise by at most one level (if they rose more, BFS would have assigned a smaller level). An ss–tt path in Gf′G_{f'} rises ℓ(t)=δf(s,t)\ell(t) = \delta_f(s, t) levels in total with steps of at most +1+1, so has at least δf(s,t)\delta_f(s, t) arcs, with equality only if every arc rises one level, i.e. a path in LfL_f using no new arc. But every LfL_f path has an arc saturated by the blocking flow and absent from Gf′G_{f'}. Thus every Gf′G_{f'} path has at least δf(s,t)+1\delta_f(s, t) + 1 arcs.

∎

Since distance lies between 1 and V−1V - 1, there are at most V−1V - 1 phases. We still need a fast blocking flow. The trick is a current-edge pointer per vertex: a DFS from ss always follows the pointed-to arc; on reaching tt, it augments and restarts at ss; if stuck at vertex vv (no useful outgoing arc), it backtracks, marks vv 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 EE pointer advances occur per phase, and each augmentation follows at most VV arcs and saturates at least one. Phase cost is O(VE)\bigO(VE) and total O(V2E)\bigO(V^2E).

InteractiveDinic phases
step 1 of 33
783635486sℓ=0aℓ=1bℓ=1cℓ=2dℓ=3eℓ=1fℓ=2gℓ=2hℓ=3tℓ=3d(s, t) by phase3phase 1phase 2phase 3phase 4
  • forward residual arc
  • reverse arc
  • DFS path
  • level ℓ (BFS distance)
Network
Phase1
Phase distance d(s,t)d(s, t)3
Flow value ∣f∣\abs{f}0
Augmentations in phase0
Pointer advances (total)0
Phase 1: BFS gives d(s,t)=3d(s, t) = 3. The level graph keeps only arcs rising exactly one level; the others (faint) cannot lie on a shortest path.
Each phase starts with BFS: numbers ℓ\ell are levels and faint arcs are outside the level graph. Advance the player: DFS follows pointers (the small dot by each vertex, on the pointed-to arc’s side), augments along paths rising one level at a time and abandons dead ends (✕), never revisiting them during the phase. The bottom strip records ss–tt distance in each phase: 3, 4, 5 and 8 in the layered network, with 1, 2, 3 and 1 augmentations. Enable ‘Hide arcs outside the level graph’ to see only the acyclic graph used by the phase. Switch to ‘Unit bipartite’: phase one matches three vertices and phase two finds a length-9 path that rearranges the entire matching.

Dinic’s famous case is unit capacities. If every capacity is 1, blocking flow takes O(E)\bigO(E) (each arc is saturated or discarded once), and there are O(min⁡(E,V2/3))\bigO(\min(\sqrt{E}, V^{2/3})) phases. If the network is additionally unit in the sense that each vertex other than ss and tt has one incoming or one outgoing edge (as in bipartite matching), there are O(V)\bigO(\sqrt V) phases and total cost O(EV)\bigO(E\sqrt V) (Even and Tarjan, 1975). The argument is elegant: after V\sqrt V phases distance is at least V\sqrt V. Remaining flow decomposes in the residual into vertex-disjoint paths (by the unit condition), each of length at least V\sqrt V, so at most V/V=VV/\sqrt V = \sqrt V remain. Each later phase increases flow by at least 1, so at most V\sqrt V more phases remain. Applied to bipartite matching, this is the Hopcroft–Karp algorithm in the next lesson.

[ ]Dinic from scratchBrowser
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 20×2020 \times 20 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 ss–tt 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 ss, with h(s)=nh(s) = n and all other heights 0, and repeats one of two operations while an active vertex uu exists:

  • Push: if a residual arc (u,v)(u, v) has h(u)=h(v)+1h(u) = h(v) + 1, send min⁡(e(u),cf(u,v))\min(e(u), c_f(u, v)) along it. Water descends one level at a time.
  • Relabel: if none exists, raise uu to h(u)=1+min⁡{h(v):(u,v)∈Ef}h(u) = 1 + \min\{h(v) : (u, v) \in E_f\}, the lowest height permitting a push.

Both operations preserve validity of hh. The key to correctness is: with valid heights, no ss–tt residual path exists. A simple path has at most n−1n - 1 arcs and each descends at most one level, so cannot descend from h(s)=nh(s) = n to h(t)=0h(t) = 0. When no active vertices remain, the preflow is a flow with no augmenting path and therefore maximum. Excess that does not fit in tt is not lost: relabeling raises stuck vertices above nn and water returns to ss through reverse arcs.

InteractivePush–relabel: water flows downhill
step 1 of 26
012345n=67height h16/1613/13sv₁e=16v₂e=13v₃v₄t
  • flow f/c
  • current push
  • excess (retained water)
  • source height n
Network
Excess at tt0
Active queuev₁, v₂
Pushes (saturating)0 (0)
Relabels0
At completion: pushes and relabels13 and 11
Initial preflow: arcs leaving ss are saturated and ss is set to height n=6n = 6. Its neighbors acquire excess and enter the queue.
The vertical axis is height: each vertex is drawn at hh, with ss at height nn (dashed purple line). The blue halo is retained excess. Step through the classic network: initial preflow fills v1v_1 and v2v_2, water descends level by level toward tt and a vertex rises when it cannot descend further. At the end, what does not fit in tt rises above nn and returns to ss. Without heuristics it takes 13 pushes and 11 relabels; enable ‘Gap heuristic’ (11 and 9) and ‘Exact initial heights’ (9 and 4) and compare counters.

Cost. If uu is active, there is a residual path from uu to ss (excess came from ss and can return), and validity of hh gives h(u)≤h(s)+n−1=2n−1h(u) \le h(s) + n - 1 = 2n - 1. Thus each vertex is relabeled O(n)\bigO(n) times: O(V2)\bigO(V^2) total. Saturating pushes are O(VE)\bigO(VE) (between two saturations of one arc, both endpoints must rise two levels). Nonsaturating pushes are O(V2E)\bigO(V^2E) by a potential argument Φ=∑u activoh(u)\Phi = \sum_{u \text{ activo}} h(u). Choosing the active vertex carefully improves the bound: FIFO gives O(V3)\bigO(V^3) and the highest-label rule O(V2E)\bigO(V^2\sqrt E).

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 tt (backward BFS). True heights guide water directly to tt instead of discovering the way through relabeling.
  • Gap. If after relabeling no vertex remains at height k<nk < n, those between kk and nn can no longer reach tt (a residual path descends at most one level per arc and would pass through height kk), so raise them at once to n+1n + 1: their excess can only return to ss.
  • 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, E1+o(1)E^{1 + o(1)}, using interior-point methods and dynamic data structures (see the module frontier).

[ ]FIFO push–relabel with heuristicsBrowser
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 tt (maximum flow, 539, is much less than what leaves ss when outgoing edges are saturated) climbs one level at a time to n=400n = 400 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 s∗s^* with edges s∗→sis^* \to s_i and supersink t∗t^* with edges tj→t∗t_j \to t^*, of infinite capacity or each source’s supply and sink’s demand.
  • Undirected edges. Edge {u,v}\{u, v\} of capacity cc becomes arcs u→vu \to v and v→uv \to u each of capacity cc. 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 cvc_v units can pass through vv, split vv into vinv_{\text{in}} and voutv_{\text{out}} joined by an edge of capacity cvc_v: edges entering vv enter vinv_{\text{in}} and outgoing edges leave voutv_{\text{out}}. Everything traversing vv 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 kk edge-disjoint paths gives flow value kk. Conversely, integrality gives an integer maximum flow, with values 0 or 1. Starting at ss and following flow-1 edges, conservation guarantees reaching tt (if a cycle forms, remove its flow without changing value); remove path edges and repeat ∣f∣\abs{f} times. Thus maximum path count equals maximum flow. A minimum cut has capacity equal to its edge count, and removing those edges disconnects tt from ss; conversely, if removing kk edges disconnects them, reachable set SS after removal gives a cut of capacity at most kk. Max-flow min-cut makes both counts equal. For the vertex version apply this to the split-vertex network (capacity 1 on each vin→voutv_{\text{in}} \to v_{\text{out}} 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 ss nor tt fixed (network edge connectivity), fix any ss and solve n−1n - 1 flows, one for each possible tt; Karger’s randomized algorithm does it without flows.

Project selection and maximum-weight closure

There are nn projects; project ii has profit pi∈Rp_i \in \R, possibly negative (a cost such as buying a machine), and requirements such as “choosing ii requires choosing jj.” Seek a closed set AA (if i∈Ai \in A and ii requires jj, then j∈Aj \in A) maximizing ∑i∈Api\sum_{i \in A} p_i. 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 AA were not closed, there would be i∈Ai \in A and j∉Aj \notin A with ii requiring jj, and infinite edge i→ji \to j would cross from SS to TT. Conversely, for closed AA, cut ({s}∪A,resto)(\{s\} \cup A, \text{resto}) crosses no infinite edge. Edges that do cross are s→is \to i with i∉Ai \notin A and pi>0p_i > 0, contributing lost profits, and i→ti \to t with i∈Ai \in A and pi<0p_i < 0, contributing paid costs. Thus c(S,T)=∑i∉A,pi>0pi+∑i∈A,pi<0(−pi)=P−∑i∈Apic(S, T) = \sum_{i \notin A, p_i > 0} p_i + \sum_{i \in A, p_i < 0} (-p_i) = P - \sum_{i \in A} p_i.

∎

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 pp a label xp∈{0,1}x_p \in \{0, 1\} (background or object), minimizing an energy with two terms:

E(x)=∑pDp(xp)+λ∑{p,q} vecinoswpq 1[xp≠xq].E(\vb{x}) = \sum_p D_p(x_p) + \lambda \sum_{\{p, q\} \text{ vecinos}} w_{pq}\,\ind[x_p \neq x_q].

The data term Dp(xp)D_p(x_p) measures how implausible the label is for pixel intensity (e.g. (Ip−μx)2/2σ2(I_p - \mu_x)^2 / 2\sigma^2, with means μ1,μ0\mu_1, \mu_0 estimated from user-marked regions). The smoothness term charges λwpq\lambda w_{pq} 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 s→ps \to p of capacity Dp(0)D_p(0) (cut if pp ends in background) and another p→tp \to t of capacity Dp(1)D_p(1), and every neighbor pair is joined by two arcs of capacity λwpq\lambda w_{pq}. A cut (S,T)(S, T) is a labeling (xp=1x_p = 1 if p∈Sp \in S) and its capacity is exactly E(x)E(\vb{x}). User seeds are imposed with infinite capacity toward ss or tt.

InteractiveImage segmentation by minimum cut
accuracy (%) versus λ with these seeds7588100036912
  • object seed
  • background seed
  • side of s (object)
  • contour = cut neighbor edges
Image
Brush
1.50
Accuracy against ground truth97.6 %
Object pixels (ground truth)169 (184)
Means μF\mu_F, μB\mu_B0.75, 0.33
Data cost495.5
Smoothness cost106.5 (71 pairs)
Energy = cut capacity602
The cut balances data and smoothness. Accuracy: 97.6 %; the best in the sweep is 97.6 % at λ = 1.50.
Synthetic noisy 28×2828 \times 28 image; blue squares are object seeds, orange squares background seeds, and blue shading marks pixels left on the ss side (object). The red boundary is the set of neighboring-pixel edges cut by the minimum cut, recomputed with Dinic in your browser after each change. Lower λ\lambda to 0: each pixel decides alone and salt-and-pepper noise appears. Raise it gradually: the boundary smooths, and near λ=11\lambda = 11 the entire object disappears except seeds. The lower curve gives accuracy against the true mask across λ\lambda. Try ‘Two lobes’: above λ≈9\lambda \approx 9 the unseeded lobe vanishes abruptly. In ‘Gradient background’, no λ\lambda exceeds 83% accuracy with uniform weights because two means do not describe the background; enable ‘Contrast-dependent weights’ and raise λ\lambda to 10.25 or more and accuracy jumps to 99.9%. Paint seeds to correct errors and enable ‘Mark pixels paying their data term’ to see where smoothness beats data.

The figure shows the tradeoff fixed by λ\lambda and two known model limitations. Shrinkage bias: the smoothness term charges boundary length, and the shortest boundary encloses only seeds, so with large λ\lambda 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 wpq=2exp⁡(−(Ip−Iq)2/2⟨(Ip−Iq)2⟩)w_{pq} = 2\exp(-(I_p - I_q)^2 / 2\langle (I_p - I_q)^2 \rangle) help: cutting is cheap at strong edges and expensive within smooth areas, so large λ\lambda 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 wpqw_{pq} 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 EpqE_{pq} is submodular, Epq(0,1)+Epq(1,0)≥Epq(0,0)+Epq(1,1)E_{pq}(0, 1) + E_{pq}(1, 0) \ge E_{pq}(0, 0) + E_{pq}(1, 1). Attracting labels admit a cut; repelling labels are generally NP-hard.

Circulations with demands and lower bounds

Sometimes each vertex vv has demand dvd_v (negative for supply, with ∑vdv=0\sum_v d_v = 0), every edge has lower bound ℓ(u,v)≤f(u,v)≤c(u,v)\ell(u, v) \le f(u, v) \le c(u, v), and the question is whether a feasible flow exists. Reduce to maximum flow in two steps. First send the lower bound: assign edge capacity c−ℓc - \ell and correct demands, dv←dv−ℓ(u,v)d_v \gets d_v - \ell(u, v) and du←du+ℓ(u,v)d_u \gets d_u + \ell(u, v). Then add supersource SS with edges S→vS \to v of capacity −dv-d_v for supply vertices and supersink TT with edges v→Tv \to T of capacity dvd_v for demand vertices. A feasible flow exists exactly when maximum flow from SS to TT saturates every edge of TT, and original flow is recovered by adding ℓ\ell to each edge.

[ ]Menger, splitting and circulationsBrowser
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 ss and of tt) 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 2+1=32 + 1 = 3.

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.

[ ]Sanitization points in a call graphBrowser
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 B∈RV×E\mat{B} \in \R^{V \times E} (Bve=1B_{ve} = 1 if edge ee leaves vv, −1-1 if it enters, 0 otherwise), flow vector f∈RE\vb{f} \in \R^E and b~s\tilde{\vb{b}}_s the row of ss:

max⁡f b~s⊤fs.a.(Bf)v=0  (v≠s,t),0≤f≤c.\max_{\vb{f}}\ \tilde{\vb{b}}_s\T\vb{f} \quad \text{s.a.} \quad (\mat{B}\vb{f})_v = 0 \ \ (v \neq s, t), \qquad \vb{0} \le \vb{f} \le \vb{c}.

Its dual has variable de≥0d_e \ge 0 for each bound fe≤cef_e \le c_e and potential pvp_v per vertex; removing redundancies gives

min⁡d,p ∑ecedes.a.duv≥pu−pv  ∀(u,v)∈E,ps−pt≥1,d≥0.\min_{\vb{d}, \vb{p}}\ \sum_e c_e d_e \quad \text{s.a.} \quad d_{uv} \ge p_u - p_v \ \ \forall (u, v) \in E, \qquad p_s - p_t \ge 1, \qquad \vb{d} \ge \vb{0}.

A cut (S,T)(S, T) gives a dual solution with pv=1[v∈S]p_v = \ind[v \in S] and duv=1[u∈S,v∈T]d_{uv} = \ind[u \in S, v \in T] of value c(S,T)c(S, T). The dual is a continuous relaxation of minimum cut: potentials can take intermediate values. Integrality of its optimum is not obvious; it follows because B\mat{B} is totally unimodular: every square minor is −1-1, 0 or 1 (each column has one +1+1 and one −1-1, 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.

[ ]The dual of maximum flow is minimum cutBrowser
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 S={s,v1,v2,v4}S = \{s, v_1, v_2, v_4\} 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 ss–tt cut, are NP-hard.

The professional version

ToolAlgorithmWhen to use
networkx.maximum_flow, minimum_cutpreflow (push–relabel) by default; also Edmonds–Karp, Dinitz, Boykov–Kolmogorovprototypes, graphs with thousands of vertices, arbitrary attributes
scipy.sparse.csgraph.maximum_flowEdmonds–Karp or Dinic, in C on CSRinteger capacities, large sparse graphs
OR-Tools SimpleMaxFlowpush–relabel with heuristicsproduction, millions of edges
Boost Graph Library, LEMONpush–relabel, Boykov–KolmogorovC++
PyMaxflowBoykov–Kolmogorovcomputer-vision grids
[ ]networkx and SciPyBrowser
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

NumericMaximum flow of a six-vertex network
The network has edges s→as \to a (10), s→bs \to b (8), a→ba \to b (6), a→ca \to c (7), b→db \to d (6), c→dc \to d (4), c→tc \to t (10), d→td \to t (12) and d→ad \to a (6). What is the maximum-flow value from ss to tt?
QuizWhere is the cut?
Ford–Fulkerson has finished with maximum flow ff. Which edge set is always a minimum cut?
QuizCorrect reductions
Which reductions to maximum flow are correct?

More than one answer may be correct.

QuizWhy h(s) = n
In push–relabel, why does a valid height function with h(s)=nh(s) = n and h(t)=0h(t) = 0 guarantee no residual path from ss to tt?
NumericProject selection by hand
Four projects: AA yields +8+8 and requires CC; BB yields +6+6 and requires CC and DD; CC costs 5 (pC=−5p_C = -5) and DD costs 7 (pD=−7p_D = -7). What is the maximum profit of a closed set?
ProofThe theorem’s three conditions
Prove: For a flow ff in a network GG the following are equivalent: (1) ff is maximum; (2) GfG_f has no augmenting path; (3) ∣f∣=c(S,T)\abs{f} = c(S, T) for some cut (S,T)(S, T).
0
We prove the cycle (1) ⇒ (2) ⇒ (3) ⇒ (1).

Step 1 of 4. How is (1) ⇒ (2) proved?

ProofEdmonds–Karp distances do not decrease
Prove: Let f′f' be the flow after an Edmonds–Karp augmentation on ff (along a shortest path of GfG_f). Then δf′(s,v)≥δf(s,v)\delta_{f'}(s, v) \ge \delta_f(s, v) for every vertex vv.
0
Suppose not, and among vertices with δf′(s,v)<δf(s,v)\delta_{f'}(s, v) < \delta_f(s, v) choose one with minimum δf′(s,v)\delta_{f'}(s, v). Let uu be predecessor of vv on a shortest path from ss to vv in Gf′G_{f'}, so δf′(s,u)=δf′(s,v)−1\delta_{f'}(s, u) = \delta_{f'}(s, v) - 1.

Step 1 of 4. What do you know about uu?

CodeProject selection with a minimum cut
Implement 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()
Shift+Enter to run

Summary

Key idea
The maximum that fits through a network equals the capacity of its narrowest bottleneck, and a maximum flow’s residual graph identifies it: vertices reachable from the source form one side of the minimum cut.
  • A flow respects capacities and conservation; a cut separates ss from tt. Net flow through any cut is ∣f∣\abs{f}, 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 O(E∣f∗∣)\bigO(E\abs{f^*}) (pseudopolynomial), and with irrational capacities it may neither terminate nor converge to the maximum.
  • Theorem: ff is maximum if and only if no augmenting path exists if and only if ∣f∣=c(S,T)\abs{f} = c(S, T) for some cut. Integer capacities admit an integer maximum flow (integrality).
  • Edmonds–Karp (shortest paths) makes O(VE)\bigO(VE) augmentations: O(VE2)\bigO(VE^2). Dinic groups equal-length paths into phases using blocking flows and current-edge pointers: O(V2E)\bigO(V^2E), and O(EV)\bigO(E\sqrt V) on unit networks such as bipartite matching.
  • Push–relabel works with preflows and heights, pushing excess downhill: O(V2E)\bigO(V^2E) generic, O(V3)\bigO(V^3) 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.