---
title: "Flows and Matchings"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 26
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/26-flows-and-matchings
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 26 — Flows and Matchings

On the day of a match, buses leave the town’s Bus Depot for the Football Ground. Every road can carry only so many buses an hour; the rule used in this chapter is that a road with a speed limit of $v$ km/h carries $v - 10$ buses an hour in each direction it is open. How many buses an hour can reach the ground? A program answers in a few lines:

```python
DEPOT, GROUND = 16, 15
net, roads = town_network()
log = []
value, flow = max_flow(net, DEPOT, GROUND, log=log)
print(f"{len(PLACES)} places, {len(net.cap)} directed road edges")
for path, delta in log:
    print(f"augment {delta:2} along {len(path) - 1:2} roads:", "-".join(map(str, path)))
print("maximum flow:", value, "buses an hour")
side, cut = min_cut(net, flow, DEPOT)
print(f"minimum cut, {sum(net.cap[e] for e in cut)} buses an hour:")
for u, v in cut:
    print(f"   road {roads[(u, v)]:2}, {PLACES[u]} > {PLACES[v]}: {net.cap[(u, v)]}")
```

***Listing 26.1.** The largest number of buses an hour from the depot (place 16) to the ground (place 15), and the roads that limit it code/bachelor-2/26-flows-and-matchings/listings/town_flow.py*

```
$ python town_flow.py
30 places, 105 directed road edges
augment 20 along  2 roads: 16-4-15
augment 40 along  2 roads: 16-7-15
augment 20 along  9 roads: 16-4-7-23-10-2-11-6-20-15
augment 20 along 10 roads: 16-24-1-23-10-2-11-6-20-19-15
augment 20 along 14 roads: 16-24-3-26-21-28-9-17-25-8-12-13-5-14-15
maximum flow: 120 buses an hour
minimum cut, 120 buses an hour:
   road 16, Hill Park > Market Hall: 40
   road 40, Fire Station > Clinic: 20
   road 11, North School > Football Ground: 20
   road 20, Swimming Pool > Football Ground: 40
```

***Output 26.1.** Five routes found one after the other, 120 buses an hour in all, and four roads that carry exactly 120 between them.*

Two numbers agree in that output: the 120 buses an hour sent, and the 120 that four roads can carry. The second is a proof that nobody can do better, since every bus from the depot to the ground has to use one of those four roads. This chapter proves that such a pair of numbers always exists, gives an algorithm that finds both in polynomial time, and then uses it for problems that do not look like traffic at all: pairing readers with reading slots, finding routes with no road in common, and choosing which projects to run.

**You already know.**

The Year 1 volume: directed graphs and their adjacency lists; breadth-first search, which finds the paths with fewest edges from a vertex; bipartite graphs, whose vertices split into two sides with every edge going from one side to the other; the [cut](#def-b2-flows-and-matchings-cut) of a graph, a split of its vertices into two parts, used there for minimum spanning trees.

## 26.1 Flow networks and cuts

**Definition 26.1 (Flow network).**

A *flow network* is a directed graph $G = (V, E)$ with two distinct vertices, the *source* $s$ and the *sink* $t$, and a *capacity* $c(u, v) \geq 0$ for each edge $(u, v)$. We set $c(u, v) = 0$ when $(u, v)$ is not an edge.

**Definition 26.2 (Flow, value).**

A *flow* is a function $f$ on the edges with

- *capacity* : $0 \leq f(u, v) \leq c(u, v)$ for every edge;
- *conservation* : for every vertex $w \neq s, t$ , what enters equals what leaves, $\sum_{u} f(u, w) = \sum_{v} f(w, v)$ .

Its *value* is what leaves the [source](#def-b2-flows-and-matchings-network), less what enters it: $|f| = \sum_{v} f(s, v) - \sum_{u} f(u, s)$. A *maximum flow* is a flow of largest value.

In [Output 26.1](#out-b2-flows-and-matchings-town) the vertices are the town’s places, the edges its roads in each direction they are open, the capacities buses an hour, and the [flow](#def-b2-flows-and-matchings-flow) the number of buses an hour planned on each road. Conservation says that buses neither appear nor vanish at a junction. The smaller network below serves for the hand computations of the chapter.

```
$ python flow.py
augment  7 along s -> a -> c -> t
augment  1 along s -> a -> d -> t
augment  4 along s -> b -> c -> a -> d -> t
maximum flow 12
flow/capacity: sa 8/8, sb 4/6, ac 3/7, ad 5/5, bc 4/6, ct 7/7, dt 5/9
reachable from s in the residual network: ['a', 'b', 'c', 's']
minimum cut: ad, ct, capacity 12
```

***Output 26.2.** A maximum [flow](#def-b2-flows-and-matchings-flow) of a network with six vertices, found in three augmentations, and the [cut](#def-b2-flows-and-matchings-cut) that proves it maximum.*

![The network of with its maximum flow, each edge labelled flow/capacity; saturated edges are red. The dashed line is the minimum cut: the edges from S to T are (a, d) and (c, t), both saturated, of total capacity 5 + 7 = 12, the value of the flow.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-flows-and-matchings/fig-f5d46b0a732f.svg)

*The network of [Output 26.2](#out-b2-flows-and-matchings-flow) with its maximum [flow](#def-b2-flows-and-matchings-flow), each edge labelled [flow](#def-b2-flows-and-matchings-flow)/capacity; saturated edges are red. The dashed line is the minimum [cut](#def-b2-flows-and-matchings-cut): the edges from $S$ to $T$ are $(a, d)$ and $(c, t)$, both saturated, of total capacity $5 + 7 = 12$, the [value](#def-b2-flows-and-matchings-flow) of the [flow](#def-b2-flows-and-matchings-flow).*

**Definition 26.3 (Cut of a flow network, capacity).**

A *cut* of a [flow network](#def-b2-flows-and-matchings-network) is a partition of $V$ into two sets $S$ and $T = V \setminus S$ with $s \in S$ and $t \in T$. Its *capacity* is $c(S, T) = \sum_{u \in S,\, v \in T} c(u,
v)$, the capacities of the edges from $S$ to $T$ only. The *net [flow](#def-b2-flows-and-matchings-flow)* across it is $f(S, T) = \sum_{u \in S,\, v \in
T} f(u, v) - \sum_{u \in T,\, v \in S} f(u, v)$.

The [cut](#def-b2-flows-and-matchings-cut) of a [flow network](#def-b2-flows-and-matchings-network) is the [cut](#def-b2-flows-and-matchings-cut) of a graph of the Year 1 volume with a side chosen for $s$ and one for $t$, and it counts only the edges that go forwards, from $S$ to $T$.

**Proposition 26.4 (Flow across a cut).**

For every [flow](#def-b2-flows-and-matchings-flow) $f$ and every [cut](#def-b2-flows-and-matchings-cut) $(S, T)$, $f(S, T) = |f|$.

**Proof.** [Exercise 26.8](#exo-b2-flows-and-matchings-8): sum the conservation equations over the vertices of $S$ other than $s$. ∎

**Corollary 26.5 (Weak duality).**

For every [flow](#def-b2-flows-and-matchings-flow) $f$ and every [cut](#def-b2-flows-and-matchings-cut) $(S, T)$, $|f| \leq c(S, T)$. So if $|f| = c(S, T)$, the [flow](#def-b2-flows-and-matchings-flow) is maximum and the [cut](#def-b2-flows-and-matchings-cut) is of minimum capacity.

**Proof.** $|f| = f(S, T) \leq \sum_{u \in S, v \in T} f(u, v) \leq \sum_{u \in S, v \in T} c(u, v) = c(S, T)$: the edges from $T$ to $S$ only subtract, and each edge from $S$ to $T$ carries at most its capacity. If $|f| = c(S, T)$, then any [flow](#def-b2-flows-and-matchings-flow) $f'$ has $|f'| \leq c(S, T) = |f|$, and any [cut](#def-b2-flows-and-matchings-cut) $(S', T')$ has $c(S', T') \geq |f| = c(S, T)$. ∎

A [cut](#def-b2-flows-and-matchings-cut) is therefore a certificate: whoever finds a [flow](#def-b2-flows-and-matchings-flow) and a [cut](#def-b2-flows-and-matchings-cut) of the same [value](#def-b2-flows-and-matchings-flow) has proved that both are optimal, and anyone can check it by adding numbers, as the last lines of [Output 26.2](#out-b2-flows-and-matchings-flow) do.

## 26.2 Residual networks and augmenting paths

A first idea is greedy: find a path from $s$ to $t$ whose edges are not full, push as much as it allows, and repeat. On the network above, the greedy idea can push $7$ along $s, a, c, t$ and $1$ along $s, a, d, t$, and then stops: $s \to a$ and $c \to t$ are full, and the only remaining path, $s, b, c, t$, uses the full edge $c \to t$. Its [value](#def-b2-flows-and-matchings-flow), $8$, is not the maximum. The way out is to allow taking back [flow](#def-b2-flows-and-matchings-flow) already sent: $4$ of the $7$ units on $a \to c$ can go through $d$ instead, which frees $c \to t$ for $4$ units coming from $b$.

**Definition 26.6 (Residual network, augmenting path).**

Given a [flow](#def-b2-flows-and-matchings-flow) $f$, the *residual capacity* of a pair of vertices is

$$
c_f(u, v) = c(u, v) - f(u, v) + f(v, u),
$$

what can still be pushed from $u$ to $v$: the unused capacity of $(u, v)$, plus the [flow](#def-b2-flows-and-matchings-flow) on $(v, u)$ that can be cancelled. The *residual network* $G_f$ has an edge $(u, v)$ whenever $c_f(u, v) > 0$. An *augmenting path* is a path from $s$ to $t$ in $G_f$.

![The residual network after the first two augmentations of (flow 7 on s, a, c, t and 1 on s, a, d, t). Solid edges are unused capacity, dashed ones flow that can be cancelled. The red path s, b, c, a, d, t is an augmenting path of bottleneck 4; its edge c a cancels 4 units of the flow on a c.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-flows-and-matchings/fig-dfadcb680e7e.svg)

*The [residual network](#def-b2-flows-and-matchings-residual) after the first two augmentations of [Output 26.2](#out-b2-flows-and-matchings-flow) ([flow](#def-b2-flows-and-matchings-flow) $7$ on $s, a, c, t$ and $1$ on $s, a, d, t$). Solid edges are unused capacity, dashed ones [flow](#def-b2-flows-and-matchings-flow) that can be cancelled. The red path $s, b, c, a, d, t$ is an augmenting path of bottleneck $4$; its edge $c \to a$ cancels $4$ units of the [flow](#def-b2-flows-and-matchings-flow) on $a \to c$.*

**Method 26.7 (Ford–Fulkerson).**

Start from the zero [flow](#def-b2-flows-and-matchings-flow). While the [residual network](#def-b2-flows-and-matchings-residual) has an augmenting path $p$: let $\delta = \min_{(u, v) \in p}
c_f(u, v)$, its *bottleneck*; for each edge $(u, v)$ of $p$, first cancel up to $\delta$ units of $f(v, u)$, then add the rest to $f(u, v)$. When no augmenting path is left, return $f$.

```python
class Network:
    def __init__(self):
        self.cap = {}  # (u, v) -> capacity; a missing pair has capacity 0
        self.adj = {}  # u -> the vertices v with (u, v) or (v, u) an edge

    def add_edge(self, u, v, c):
        self.cap[(u, v)] = self.cap.get((u, v), 0) + c
        for a, b in [(u, v), (v, u)]:
            self.adj.setdefault(a, [])
            if b not in self.adj[a]:
                self.adj[a].append(b)  # residual edges go both ways

    def residual(self, flow, u, v):
        """What can still be pushed from u to v: unused capacity, plus flow v -> u
        that can be cancelled."""
        return self.cap.get((u, v), 0) - flow.get((u, v), 0) + flow.get((v, u), 0)
```

***Listing 26.2.** A [flow network](#def-b2-flows-and-matchings-network): capacities, and the [residual capacity](#def-b2-flows-and-matchings-residual) of a pair for a given [flow](#def-b2-flows-and-matchings-flow) code/bachelor-2/26-flows-and-matchings/listings/maxflow.py*

```python
def shortest_path(net, flow, s, t):
    """A shortest augmenting path by breadth-first search, as a list of vertices."""
    parent, queue = {s: None}, deque([s])
    while queue:
        u = queue.popleft()
        for v in net.adj.get(u, []):
            if v not in parent and net.residual(flow, u, v) > 0:
                parent[v] = u
                if v == t:
                    path = [t]
                    while path[-1] != s:
                        path.append(parent[path[-1]])
                    return path[::-1]
                queue.append(v)
    return None


def augment(net, flow, path):
    """Push the bottleneck along path, cancelling reverse flow first."""
    pairs = list(zip(path, path[1:]))
    delta = min(net.residual(flow, u, v) for u, v in pairs)
    for u, v in pairs:
        back = min(delta, flow.get((v, u), 0))  # cancel flow v -> u first
        flow[(v, u)] = flow.get((v, u), 0) - back
        flow[(u, v)] = flow.get((u, v), 0) + delta - back
    return delta


def max_flow(net, s, t, find=shortest_path, log=None):
    """Ford-Fulkerson; with shortest paths, Edmonds-Karp. Returns (value, flow)."""
    flow, value = {}, 0
    while (path := find(net, flow, s, t)) is not None:
        delta = augment(net, flow, path)
        value += delta
        if log is not None:
            log.append((path, delta))
    return value, {e: f for e, f in flow.items() if f > 0}
```

***Listing 26.3.** Ford–Fulkerson; the path-finding function is a parameter, by default the breadth-first search code/bachelor-2/26-flows-and-matchings/listings/maxflow.py*

**Lemma 26.8 (Augmenting keeps a flow).**

If $f$ is a [flow](#def-b2-flows-and-matchings-flow) and $p$ an augmenting path of bottleneck $\delta$, the result $f'$ of the augmentation is a [flow](#def-b2-flows-and-matchings-flow) of [value](#def-b2-flows-and-matchings-flow) $|f| + \delta$.

**Proof.** On an edge $(u, v)$ of $p$, $\delta \leq c_f(u, v) = (c(u, v) - f(u, v)) + f(v, u)$. The listing removes $b = \min(\delta,
f(v, u))$ from $f(v, u)$, which stays $\geq 0$, and adds $\delta - b$ to $f(u, v)$; if $b < \delta$ then $b = f(v, u)$ and $\delta - b \leq c(u, v) - f(u, v)$, so the capacity holds. The change makes the net [flow](#def-b2-flows-and-matchings-flow) from $u$ to $v$ grow by exactly $\delta$. At an inner vertex $w$ of $p$, the net [flow](#def-b2-flows-and-matchings-flow) from its predecessor to $w$ and from $w$ to its successor both grow by $\delta$, so $w$ stays balanced. The path leaves $s$ once and never returns to it (a path repeats no vertex), so the net [flow](#def-b2-flows-and-matchings-flow) out of $s$, $|f|$, grows by $\delta$. ∎

**Theorem 26.9 (Termination and integrality).**

If all capacities are integers, Ford–Fulkerson stops after at most $C = \sum_{v} c(s, v)$ augmentations, whatever the augmenting paths chosen, and returns a [flow](#def-b2-flows-and-matchings-flow) whose values are all integers. In particular, a network with integer capacities has a maximum [flow](#def-b2-flows-and-matchings-flow) with integer values.

**Proof.** By induction, the [flow](#def-b2-flows-and-matchings-flow) stays integral: the residual capacities of an integral [flow](#def-b2-flows-and-matchings-flow) are integers, so is the bottleneck $\delta$, and each augmentation adds or subtracts $\delta$. Then $\delta \geq 1$, and by [Lemma 26.8](#lem-b2-flows-and-matchings-augment) each augmentation raises the [value](#def-b2-flows-and-matchings-flow) by at least $1$. The [value](#def-b2-flows-and-matchings-flow) never exceeds the capacity $C$ of the [cut](#def-b2-flows-and-matchings-cut) $(\{s\}, V
\setminus \{s\})$ ([Corollary 26.5](#cor-b2-flows-and-matchings-weak-duality)), so there are at most $C$ augmentations. The [flow](#def-b2-flows-and-matchings-flow) returned is maximum by the next theorem. ∎

## 26.3 The max-flow min-cut theorem

**Theorem 26.10 (Max-flow min-cut).**

For a [flow](#def-b2-flows-and-matchings-flow) $f$ the following are equivalent:

1. $f$ is a maximum [flow](#def-b2-flows-and-matchings-flow) ;
2. the [residual network](#def-b2-flows-and-matchings-residual) $G_f$ has no augmenting path;
3. $|f| = c(S, T)$ for some [cut](#def-b2-flows-and-matchings-cut) $(S, T)$ .

So the [value](#def-b2-flows-and-matchings-flow) of a maximum [flow](#def-b2-flows-and-matchings-flow) equals the capacity of a minimum [cut](#def-b2-flows-and-matchings-cut), and when no augmenting path is left, the vertices reachable from $s$ in $G_f$ form the [source](#def-b2-flows-and-matchings-network) side of a minimum [cut](#def-b2-flows-and-matchings-cut).

**Proof.** (1)$\Rightarrow$(2): an augmenting path would give a [flow](#def-b2-flows-and-matchings-flow) of larger [value](#def-b2-flows-and-matchings-flow), by [Lemma 26.8](#lem-b2-flows-and-matchings-augment).

(2)$\Rightarrow$(3): let $S$ be the set of vertices reachable from $s$ in $G_f$, and $T = V \setminus S$. Then $s \in S$, and $t \in T$ since there is no augmenting path. For $u \in S$ and $v \in T$, $c_f(u, v) = 0$, otherwise $v$ would be reachable. As $c_f(u, v) = (c(u, v) - f(u, v)) + f(v, u)$ is a sum of two non-negative terms, $f(u, v) = c(u, v)$ and $f(v, u) = 0$. Every edge from $S$ to $T$ is saturated and every edge from $T$ to $S$ empty, so by [Proposition 26.4](#prop-b2-flows-and-matchings-flow-across-cut), $|f| = f(S, T) = c(S, T)$.

(3)$\Rightarrow$(1): [Corollary 26.5](#cor-b2-flows-and-matchings-weak-duality). ∎

The function `min_cut` below is the proof of (2)$\Rightarrow$(3) turned into code: a search in the [residual network](#def-b2-flows-and-matchings-residual) from $s$, then the edges that leave what it reached.

```python
def min_cut(net, flow, s):
    """The vertices reachable from s in the residual network; the edges leaving them."""
    seen, stack = {s}, [s]
    while stack:
        u = stack.pop()
        for v in net.adj.get(u, []):
            if v not in seen and net.residual(flow, u, v) > 0:
                seen.add(v)
                stack.append(v)
    edges = [(u, v) for (u, v), c in net.cap.items()
             if u in seen and v not in seen and c > 0]
    return seen, sorted(edges, key=str)
```

***Listing 26.4.** The minimum [cut](#def-b2-flows-and-matchings-cut) read from the [residual network](#def-b2-flows-and-matchings-residual) of a maximum [flow](#def-b2-flows-and-matchings-flow) code/bachelor-2/26-flows-and-matchings/listings/maxflow.py*

In [Output 26.1](#out-b2-flows-and-matchings-town) the [cut](#def-b2-flows-and-matchings-cut) is not where one would look first: two of its four roads end at the ground, but the other two, from Hill Park to the Market Hall and from the Fire Station to the Clinic, are in the middle of the town. A network can also have several minimum [cuts](#def-b2-flows-and-matchings-cut); the problem at the end of the chapter shows why that matters when one asks which road to widen.

## 26.4 Choosing the augmenting path: Edmonds–Karp

[Theorem 26.9](#thm-b2-flows-and-matchings-integrality) bounds the number of augmentations by the capacities, not by the size of the graph, and the bound can be reached. In the network below, each augmentation along $s, a, b, t$ or $s, b, a, t$ can push only $1$, through the middle edge or back against it.

![The bad example: the maximum flow is 2C. Paths through the middle edge, alternately forwards (s, a, b, t) and backwards (s, b, a, t, which cancels the unit just sent), push 1 each and take 2C augmentations; the two paths of two edges take 2.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-flows-and-matchings/fig-114096d70919.svg)

*The bad example: the maximum [flow](#def-b2-flows-and-matchings-flow) is $2C$. Paths through the middle edge, alternately forwards ($s, a, b, t$) and backwards ($s, b, a, t$, which cancels the unit just sent), push $1$ each and take $2C$ augmentations; the two paths of two edges take $2$.*

```
$ python bad_example.py
C =   10, narrowest paths: flow   20,   20 augmentations, first sabt, sbat
C =   10, shortest  paths: flow   20,    2 augmentations, first sat, sbt
C =  100, narrowest paths: flow  200,  200 augmentations, first sabt, sbat
C =  100, shortest  paths: flow  200,    2 augmentations, first sat, sbt
C = 1000, narrowest paths: flow 2000, 2000 augmentations, first sabt, sbat
C = 1000, shortest  paths: flow 2000,    2 augmentations, first sat, sbt
```

***Output 26.3.** The narrowest augmenting path each time against the shortest one.*

The listing `bad_example.py` picks, among all augmenting paths, one of smallest bottleneck, the worst possible choice. With capacities written on $\log_2 C$ bits, $2C$ augmentations is exponential in the size of the input. With irrational capacities the method may even never stop. Breadth-first search avoids both.

**Method 26.11 (Edmonds–Karp).**

Ford–Fulkerson in which each augmenting path is a shortest one, in number of edges, found by breadth-first search in the [residual network](#def-b2-flows-and-matchings-residual). It is the default of [Listing 26.3](#lst-b2-flows-and-matchings-maxflow).

Write $\delta_f(v)$ for the distance from $s$ to $v$ in $G_f$, in number of edges ($\infty$ if $v$ is unreachable).

**Lemma 26.12 (Distances never decrease).**

In Edmonds–Karp, if $f'$ is the [flow](#def-b2-flows-and-matchings-flow) after an augmentation of $f$, then $\delta_{f'}(v) \geq \delta_f(v)$ for every vertex $v$.

**Proof.** [Exercise 26.11](#exo-b2-flows-and-matchings-11). ∎

The paths of [Output 26.1](#out-b2-flows-and-matchings-town) illustrate it: their lengths are 2, 2, 9, 10 and 14 roads.

**Theorem 26.13 (Edmonds–Karp bound).**

Edmonds–Karp makes at most $|V| \cdot |E|$ augmentations, and runs in time $O(|V| \cdot |E|^2)$, whatever the capacities.

**Proof.** Call an edge $(u, v)$ of an augmenting path *critical* if its [residual capacity](#def-b2-flows-and-matchings-residual) equals the bottleneck; each augmentation has one, and removes it from the [residual network](#def-b2-flows-and-matchings-residual). Since the path is a shortest path, $\delta_f(v) = \delta_f(u) + 1$. For $(u, v)$ to be critical again, it must first come back into the [residual network](#def-b2-flows-and-matchings-residual), which happens only when a later augmentation, with [flow](#def-b2-flows-and-matchings-flow) $g$, uses $(v, u)$; then $\delta_g(u) = \delta_g(v) + 1$. By [Lemma 26.12](#lem-b2-flows-and-matchings-monotone), $\delta_g(v) \geq \delta_f(v)$, so

$$
\delta_g(u) = \delta_g(v) + 1 \geq \delta_f(v) + 1 = \delta_f(u) + 2.
$$

Between two times $(u, v)$ is critical, the distance of $u$ grows by at least $2$. It starts at $\geq 0$ and stays at most $|V| - 2$ while $u$ is on an augmenting path, so $(u, v)$ is critical at most $|V|/2$ times. The [residual network](#def-b2-flows-and-matchings-residual) has at most $2|E|$ possible edges, so there are at most $|V| \cdot |E|$ augmentations. Each costs one breadth-first search and one pass over the path, $O(|E|)$ when every vertex has an edge, which gives $O(|V| \cdot |E|^2)$. ∎

The bound does not mention the capacities: the algorithm is polynomial in the size of the graph alone. Faster methods exist, such as push–relabel algorithms in $O(|V|^3)$ and more recent ones close to linear time, but they rest on the same theorem.

**History.**

Lester Ford and Delbert Fulkerson published the [max-flow](#def-b2-flows-and-matchings-flow) [min-cut](#def-b2-flows-and-matchings-cut) theorem and their method in 1956. Jack Edmonds and Richard Karp showed in 1972 that shortest augmenting paths give a bound that depends only on the size of the network.

## 26.5 Bipartite matchings

Five readers want a slot in the reading room, each available on some days, and each day has one seat. Pairing them is a [matching](#def-b2-flows-and-matchings-matching) problem.

**Definition 26.14 (Matching).**

A *matching* of an undirected graph is a set $M$ of edges no two of which share an end. A vertex is *matched* if it is an end of an edge of $M$, *free* otherwise. A *maximum matching* has as many edges as possible; a *perfect matching* matches every vertex.

For a bipartite graph with sides $L$ and $R$, add a [source](#def-b2-flows-and-matchings-network) $s$ with an edge of capacity $1$ to every vertex of $L$, a [sink](#def-b2-flows-and-matchings-network) $t$ with an edge of capacity $1$ from every vertex of $R$, and direct the edges from $L$ to $R$ with capacity $1$. By [Theorem 26.9](#thm-b2-flows-and-matchings-integrality) there is a maximum [flow](#def-b2-flows-and-matchings-flow) with values in $\{0, 1\}$; its edges with [flow](#def-b2-flows-and-matchings-flow) $1$ between $L$ and $R$ form a [matching](#def-b2-flows-and-matchings-matching), since each $u \in L$ receives at most $1$ and each $v \in R$ sends at most $1$. Conversely, a [matching](#def-b2-flows-and-matchings-matching) gives a [flow](#def-b2-flows-and-matchings-flow) of the same [value](#def-b2-flows-and-matchings-flow). A maximum [matching](#def-b2-flows-and-matchings-matching) is a maximum [flow](#def-b2-flows-and-matchings-flow).

The [flow](#def-b2-flows-and-matchings-flow) formulation can be specialised. In the [residual network](#def-b2-flows-and-matchings-residual), a path from $s$ goes to a free vertex of $L$, then alternates: forwards along an edge not in the [matching](#def-b2-flows-and-matchings-matching), backwards along an edge of the [matching](#def-b2-flows-and-matchings-matching), and ends at a free vertex of $R$.

**Definition 26.15 (Alternating and augmenting paths).**

Relative to a [matching](#def-b2-flows-and-matchings-matching) $M$, an *alternating path* is a path whose edges are alternately out of $M$ and in $M$. An *augmenting path* is an alternating path whose two ends are free.

An augmenting path has one more edge out of $M$ than in it. Exchanging them, that is, replacing $M$ by the symmetric difference $M \oplus p$, gives a [matching](#def-b2-flows-and-matchings-matching) with one more edge.

```python
def augmenting_path(u, adj, match, seen):
    """Try to match left vertex u: take a free neighbour, or one whose partner can be
    moved to another neighbour. Returns True if the matching grew."""
    for v in adj[u]:
        if v in seen:
            continue
        seen.add(v)
        if v not in match or augmenting_path(match[v], adj, match, seen):
            match[v] = u  # flip the alternating path
            return True
    return False


def max_matching(adj, log=None):
    """adj: left vertex -> its right neighbours. Returns {right: left}."""
    match = {}
    for u in adj:
        before = dict(match)
        if augmenting_path(u, adj, match, set()) and log is not None:
            log.append((u, {v: w for v, w in match.items() if before.get(v) != w}))
    return match
```

***Listing 26.5.** Maximum bipartite [matching](#def-b2-flows-and-matchings-matching): from each left vertex, a depth-first search for an augmenting path code/bachelor-2/26-flows-and-matchings/listings/matching.py*

```
$ python matching_demo.py
Ada: new pairs Ada-Mon
Ben: new pairs Ben-Mon, Ada-Tue
Cy : new pairs Cy-Wed
Dee: new pairs Dee-Wed, Cy-Thu
Eve: new pairs Eve-Wed, Dee-Fri
matching: Ada-Tue, Ben-Mon, Cy-Thu, Dee-Fri, Eve-Wed
size 5 = maximum flow 5
```

***Output 26.4.** The [matching](#def-b2-flows-and-matchings-matching) of five readers with five days, and the same number as a maximum [flow](#def-b2-flows-and-matchings-flow).*

![Before Eve’s turn in : the matching is drawn in thick lines, the other edges in grey. The red augmenting path Eve, Wed, Dee, Fri starts and ends at free vertices; its middle edge (double line) is in the matching. Exchanging gives Eve–Wed and Dee–Fri, one pair more.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-flows-and-matchings/fig-7659f8368398.svg)

*Before Eve’s turn in [Output 26.4](#out-b2-flows-and-matchings-matching): the [matching](#def-b2-flows-and-matchings-matching) is drawn in thick lines, the other edges in grey. The red augmenting path Eve, Wed, Dee, Fri starts and ends at free vertices; its middle edge (double line) is in the [matching](#def-b2-flows-and-matchings-matching). Exchanging gives Eve–Wed and Dee–Fri, one pair more.*

**Theorem 26.16 (Berge).**

A [matching](#def-b2-flows-and-matchings-matching) $M$ is maximum if and only if there is no augmenting path relative to $M$.

**Proof.** If there is an augmenting path $p$, then $M \oplus p$ is a larger [matching](#def-b2-flows-and-matchings-matching). Conversely, suppose $M$ is not maximum and let $M^*$ be a larger [matching](#def-b2-flows-and-matchings-matching). In the graph with edges $M \oplus M^*$, every vertex has degree at most $2$, one edge of each [matching](#def-b2-flows-and-matchings-matching); its connected components are therefore paths and cycles whose edges alternate between $M$ and $M^*$. A cycle that alternates has as many edges of each. Since $|M^*| > |M|$, some path has more edges of $M^*$ than of $M$; it starts and ends with an edge of $M^*$, and its ends are free in $M$ (an end matched in $M$ would have its $M$-edge in the component). It is an augmenting path relative to $M$. ∎

The listing calls the search once from each left vertex, with fresh marks each time. A search visits each edge at most once, so the whole costs $O(|L| \cdot |E|)$. It is enough to try each left vertex once: a left vertex from which no augmenting path starts never gets one after later augmentations, a fact we admit ([Exercise 26.6](#exo-b2-flows-and-matchings-6) shows what goes wrong when the marks are shared between searches).

**Definition 26.17 (Vertex cover).**

A *vertex cover* of a graph is a set $C$ of vertices such that every edge has at least one end in $C$.

Every [vertex cover](#def-b2-flows-and-matchings-vertex-cover) has at least as many vertices as any [matching](#def-b2-flows-and-matchings-matching) has edges, since the edges of a [matching](#def-b2-flows-and-matchings-matching) have distinct ends and each needs one in the cover. In bipartite graphs the two numbers meet.

**Theorem 26.18 (Kőnig).**

In a bipartite graph, the largest [matching](#def-b2-flows-and-matchings-matching) and the smallest [vertex cover](#def-b2-flows-and-matchings-vertex-cover) have the same size.

**Proof.** Take the network of [matchings](#def-b2-flows-and-matchings-matching), but with capacity $|L| + 1$ on the edges from $L$ to $R$; integral [flows](#def-b2-flows-and-matchings-flow) are still [matchings](#def-b2-flows-and-matchings-matching), so the maximum [flow](#def-b2-flows-and-matchings-flow) is the size $\nu$ of a maximum [matching](#def-b2-flows-and-matchings-matching). Let $(S, T)$ be a minimum [cut](#def-b2-flows-and-matchings-cut); its capacity is $\nu$, at most $|L|$ (the [cut](#def-b2-flows-and-matchings-cut) $(\{s\}, V \setminus \{s\})$ has capacity $|L|$), so no edge from $L$ to $R$ goes from $S$ to $T$. Its capacity counts the edges $s \to u$ with $u \in L \cap T$ and $v \to t$ with $v \in R \cap S$, so $\nu = |L \cap T| +
|R \cap S|$. The set $C = (L \cap T) \cup (R \cap S)$ is a [vertex cover](#def-b2-flows-and-matchings-vertex-cover): an edge $u, v$ with neither end in $C$ would have $u \in S$ and $v \in T$, an edge from $L$ to $R$ across the [cut](#def-b2-flows-and-matchings-cut). So the smallest [vertex cover](#def-b2-flows-and-matchings-vertex-cover) has at most $\nu$ vertices, and at least $\nu$ by the remark above. ∎

[Exercise 26.12](#exo-b2-flows-and-matchings-12) builds the cover from a maximum [matching](#def-b2-flows-and-matchings-matching) directly, with [alternating paths](#def-b2-flows-and-matchings-alternating).

**Theorem 26.19 (Hall).**

A bipartite graph with sides $L$ and $R$ has a [matching](#def-b2-flows-and-matchings-matching) that matches every vertex of $L$ if and only if every set $A
\subseteq L$ has at least $|A|$ neighbours: $|N(A)| \geq |A|$.

**Proof.** If such a [matching](#def-b2-flows-and-matchings-matching) exists, the partners of the vertices of $A$ are $|A|$ distinct neighbours. Conversely, suppose no [matching](#def-b2-flows-and-matchings-matching) matches all of $L$. By Kőnig’s theorem there is a [vertex cover](#def-b2-flows-and-matchings-vertex-cover) $C$ with $|C| < |L|$. Let $A = L \setminus
C$. Every edge from a vertex of $A$ must be covered by its other end, so $N(A) \subseteq C \cap R$, and

$$
|N(A)| \leq |C \cap R| = |C| - |C \cap L| < |L| - |C \cap L| = |A|. \qedhere
$$

∎

Hall’s condition is checked set by set, and there are $2^{|L|}$ sets. The [flow](#def-b2-flows-and-matchings-flow) finds a violating set without trying them: the readers on the [source](#def-b2-flows-and-matchings-network) side of a minimum [cut](#def-b2-flows-and-matchings-cut) ([Exercise 26.10](#exo-b2-flows-and-matchings-10)).

```python
ADJ = {"Ada": ["Mon", "Tue"], "Ben": ["Mon"], "Cy": ["Tue", "Wed", "Thu"],
       "Dee": ["Wed", "Fri"], "Eve": ["Mon", "Wed"], "Fay": ["Mon", "Tue"]}
SLOTS = sorted({v for slots in ADJ.values() for v in slots})
net = Network()
for u, slots in ADJ.items():
    net.add_edge("s", u, 1)
    for v in slots:
        net.add_edge(u, v, len(ADJ))  # "infinite": more than any cut through s
for v in SLOTS:
    net.add_edge(v, "t", 1)
value, flow = max_flow(net, "s", "t")
side, _ = min_cut(net, flow, "s")
readers = sorted(u for u in ADJ if u in side)
slots = sorted({v for u in readers for v in ADJ[u]})
print(f"{len(ADJ)} readers, {len(SLOTS)} slots, at most {value} matched")
print(f"the readers {readers} accept only the {len(slots)} slots {slots}")
```

***Listing 26.6.** When a sixth reader makes a perfect [matching](#def-b2-flows-and-matchings-matching) impossible, the minimum [cut](#def-b2-flows-and-matchings-cut) names the readers who compete for too few days code/bachelor-2/26-flows-and-matchings/listings/hall.py*

```
$ python hall.py
6 readers, 5 slots, at most 5 matched
the readers ['Ada', 'Ben', 'Fay'] accept only the 2 slots ['Mon', 'Tue']
```

***Output 26.5.** Three readers available on two days only: Hall’s condition fails for them.*

## 26.6 Problems modelled as flows

Much of the use of maximum [flows](#def-b2-flows-and-matchings-flow) is in reductions: a problem that mentions no [flow](#def-b2-flows-and-matchings-flow) is turned into a network whose maximum [flow](#def-b2-flows-and-matchings-flow) or minimum [cut](#def-b2-flows-and-matchings-cut) is the answer.

**Routes with no road in common.**

**Definition 26.20 (Edge-disjoint paths).**

Paths are *edge-disjoint* if no edge belongs to two of them. A set of edges *separates* $t$ from $s$ if every path from $s$ to $t$ uses one of them.

**Theorem 26.21 (Menger).**

In a directed graph, the largest number of [edge-disjoint paths](#def-b2-flows-and-matchings-disjoint) from $s$ to $t$ equals the smallest number of edges that separate $t$ from $s$.

**Proof.** Give every edge capacity $1$. [Edge-disjoint paths](#def-b2-flows-and-matchings-disjoint) carry together a [flow](#def-b2-flows-and-matchings-flow) of [value](#def-b2-flows-and-matchings-flow) their number, so the largest number of paths is at most the maximum [flow](#def-b2-flows-and-matchings-flow). Conversely, take an integral maximum [flow](#def-b2-flows-and-matchings-flow), of [value](#def-b2-flows-and-matchings-flow) $k$, with values in $\{0, 1\}$. From $s$, follow edges of [flow](#def-b2-flows-and-matchings-flow) $1$: conservation lets the walk leave every vertex it enters, until it reaches $t$; if it comes back to a vertex, drop the loop. Removing the [flow](#def-b2-flows-and-matchings-flow) on this path gives a [flow](#def-b2-flows-and-matchings-flow) of [value](#def-b2-flows-and-matchings-flow) $k - 1$; repeating gives $k$ [edge-disjoint paths](#def-b2-flows-and-matchings-disjoint). So the largest number of paths is the maximum [flow](#def-b2-flows-and-matchings-flow). A minimum [cut](#def-b2-flows-and-matchings-cut) has capacity the number of its edges from $S$ to $T$, and these separate $t$ from $s$; conversely, the vertices still reachable from $s$ after removing a separating set $F$ form a [cut](#def-b2-flows-and-matchings-cut) whose edges from $S$ to $T$ are all in $F$. So the smallest separating set is a minimum [cut](#def-b2-flows-and-matchings-cut), and [Theorem 26.10](#thm-b2-flows-and-matchings-maxflow-mincut) concludes. ∎

For roads that can be travelled both ways, each road becomes two opposite edges of capacity $1$; a maximum [flow](#def-b2-flows-and-matchings-flow) found by augmentation never uses both, because the second would cancel the first.

```
$ python disjoint_paths.py
Station to Hospital: 3 routes with no road in common; a cut of 3 roads
    2-9-17-25-8
    2-10-23-7-15-20-13-12-8
    2-11-6-12-30-8
Bus Depot to Football Ground: 3 routes with no road in common; a cut of 3 roads
    16-4-15
    16-7-15
    16-24-1-23-10-2-11-6-20-15
Lighthouse Café to Town Square: 3 routes with no road in common; a cut of 3 roads
    30-8-12-6-11-9-10-23-1
    30-12-13-20-15-4-16-24-1
    30-25-17-9-28-21-26-1
```

***Output 26.6.** Three pairs of places, each joined by three routes with no road in common.*

**Assignment with capacities.** When the reading room has several seats a day, the edge from a day to the [sink](#def-b2-flows-and-matchings-network) gets the number of seats as capacity, and the [flow](#def-b2-flows-and-matchings-flow) places as many readers as possible; a reader who can come only once a week keeps an edge of capacity $1$ from the [source](#def-b2-flows-and-matchings-network) ([Exercise 26.9](#exo-b2-flows-and-matchings-9)).

**Choosing projects.** The library can run projects that each bring a yearly profit, but each needs equipment that has to be bought, and the equipment is shared. Which projects should it run? Put an edge from $s$ to each project, of capacity its profit; an edge from each piece of equipment to $t$, of capacity its cost; and an edge of very large capacity from each project to each piece of equipment it needs. A [cut](#def-b2-flows-and-matchings-cut) of finite capacity whose [source](#def-b2-flows-and-matchings-network) side contains a project must contain its equipment, else a large edge would cross it. Its capacity is the profits of the projects left out plus the costs of the equipment bought, which is the total of all profits minus the net profit of the projects run. A minimum [cut](#def-b2-flows-and-matchings-cut) gives the best choice.

```
$ python selection.py
run: reading club, film nights, map room, story hour; buy: projector, big table, screen
profit 10 = total profits 31 - minimum cut 21
best of all 32 choices: 10 with reading club, film nights, map room, story hour
```

***Output 26.7.** The library’s projects chosen by a minimum [cut](#def-b2-flows-and-matchings-cut), checked against the 32 choices.*

**History.**

The combinatorial theorems came first. Karl Menger published his theorem on disjoint paths in 1927, in a paper on the theory of curves; Dénes Kőnig proved his theorem on bipartite graphs in 1931, and Jenő Egerváry independently the same year in a more general form with weights; Philip Hall published his condition in 1935. The [max-flow](#def-b2-flows-and-matchings-flow) [min-cut](#def-b2-flows-and-matchings-cut) theorem of 1956 contains them all.

## 26.7 Exercises

**Exercise 26.1 ★.**

On the network of [Output 26.2](#out-b2-flows-and-matchings-flow), which of the following are [flows](#def-b2-flows-and-matchings-flow), and of which [value](#def-b2-flows-and-matchings-flow)? $f_1$: $sa\,7$, $sb\,5$, $ac\,5$, $ad\,2$, $bc\,5$, $ct\,7$, $dt\,2$; $f_2$: $sa\,8$, $sb\,6$, $ac\,3$, $ad\,5$, $bc\,6$, $ct\,9$, $dt\,5$; $f_3$: $sa\,6$, $sb\,6$, $ac\,1$, $ad\,5$, $bc\,6$, $ct\,7$, $dt\,5$. Check with `exo_is_flow.py`.

**Solution of Exercise 26.1.**

$f_1$ respects the capacities but not conservation at $c$: $5 + 5 = 10$ enter and $7$ leave. $f_2$ is balanced but puts $9$ on $c \to t$, whose capacity is $7$; its [value](#def-b2-flows-and-matchings-flow) $14$ would also exceed the [cut](#def-b2-flows-and-matchings-cut) of capacity $12$. $f_3$ is a [flow](#def-b2-flows-and-matchings-flow): at $a$, $6 = 1 + 5$; at $b$, $6 = 6$; at $c$, $1 + 6 = 7$; at $d$, $5 = 5$; its [value](#def-b2-flows-and-matchings-flow) is $6 + 6 = 12$.

```
$ python exo_is_flow.py
f1: over capacity [], not conserved at ['c'], value 12
f2: over capacity ['ct'], not conserved at [], value 14
f3: over capacity [], not conserved at [], value 12
```

***Output 26.9.** The three candidates checked.*

**Exercise 26.2 ★.**

In `exo_no_reverse.py`, a network whose [residual capacity](#def-b2-flows-and-matchings-residual) is only the unused capacity of each edge is given to the same algorithm. What [value](#def-b2-flows-and-matchings-flow) does it find on the network of [Output 26.2](#out-b2-flows-and-matchings-flow), and why? Which line of [Listing 26.2](#lst-b2-flows-and-matchings-network) does it miss?

**Solution of Exercise 26.2.**

```
$ python exo_no_reverse.py
Network   12: sact, sadt, sbcadt
Forward    8: sact, sadt
```

***Output 26.10.** With and without the reverse residual edges.*

Without reverse edges the search finds $s, a, c, t$ and $s, a, d, t$, then stops at $8$: every remaining path to $t$ needs $c \to t$, which is full, or $a \to d$ entered from $a$, which $s \to a$ can no longer feed. The [flow](#def-b2-flows-and-matchings-flow) $12$ needs the path $s, b, c, a, d, t$, which sends $4$ units back against $a \to c$. The version misses the term $+ f(v, u)$ of the [residual capacity](#def-b2-flows-and-matchings-residual), at the end of line 21 of [Listing 26.2](#lst-b2-flows-and-matchings-network).

**Exercise 26.3 ★.**

Find a maximum [flow](#def-b2-flows-and-matchings-flow) and a minimum [cut](#def-b2-flows-and-matchings-cut) by hand for the network with edges $s \to x$ (9), $s \to y$ (7), $x \to y$ (3), $x \to z$ (4), $y \to w$ (6), $z \to y$ (2), $z \to t$ (5), $w \to t$ (7). Then check with `exo_maxflow.py`.

**Solution of Exercise 26.3.**

The shortest paths $s, x, z, t$ (bottleneck $4$, at $x \to z$) and $s, y, w, t$ (bottleneck $6$, at $y \to w$) give $10$. The vertices reachable from $s$ afterwards are $s$, $x$ and $y$: $x \to y$ still has room, but $x \to z$ and $y \to
w$ are full. The [cut](#def-b2-flows-and-matchings-cut) $(\{s, x, y\}, \{z, w, t\})$ has capacity $4 + 6 = 10$; the edge $z \to y$ goes from $T$ to $S$ and does not count.

```
$ python exo_maxflow.py
augment 4 along sxzt
augment 6 along sywt
maximum flow 10; cut xz, yw; side ['s', 'x', 'y']
```

***Output 26.11.** The same [flow](#def-b2-flows-and-matchings-flow) and [cut](#def-b2-flows-and-matchings-cut) by program.*

**Exercise 26.4 ★.**

In the bad example, show that the augmenting paths $s, a, b, t$ and $s, b, a, t$, taken alternately, take exactly $2C$ augmentations, and that breadth-first search takes $2$. Compare with [Output 26.3](#out-b2-flows-and-matchings-bad).

**Solution of Exercise 26.4.**

After $s, a, b, t$ the middle edge is full and its residual is $1$ backwards; $s, b, a, t$ then uses it backwards, cancels the unit, and leaves the middle edge empty again. Each such pair raises the [flow](#def-b2-flows-and-matchings-flow) on each of the four outer edges by $1$, and each path has bottleneck $1$, so it takes $2C$ augmentations to reach $2C$, as long as no outer edge is full. Breadth-first search finds the two paths of two edges first, each of bottleneck $C$, and then $s$ has no residual edge left: $2$ augmentations.

**Exercise 26.5 ★★.**

Take the [flow](#def-b2-flows-and-matchings-flow) $f_3$ of [Exercise 26.1](#exo-b2-flows-and-matchings-1). Compute its [residual network](#def-b2-flows-and-matchings-residual), the vertices reachable from $s$, and deduce without any further computation that $f_3$ is maximum. Check with `exo_mincut.py`.

**Solution of Exercise 26.5.**

```
$ python exo_mincut.py
residual s->a: 2
residual a->c: 6
residual c->b: 6
residual b->s: 6
residual a->d: 0
residual d->t: 4
reachable: ['a', 'b', 'c', 's']; cut ad, ct
```

***Output 26.12.** A few residual capacities of $f_3$, and the vertices reachable from $s$.*

From $s$, only $s \to a$ has room ($2$); from $a$, the [flow](#def-b2-flows-and-matchings-flow) $1$ on $a \to c$ leaves $6$; from $c$, the $6$ units on $b
\to c$ can be cancelled, which reaches $b$. The edges $a \to d$ and $c \to t$ are full, and $b \to c$ is full forwards. So $S = \{s, a, b, c\}$, and the [cut](#def-b2-flows-and-matchings-cut) $(S, \{d, t\})$ has capacity $5 + 7 = 12 = |f_3|$. By [Corollary 26.5](#cor-b2-flows-and-matchings-weak-duality), $f_3$ is maximum. It is not the [flow](#def-b2-flows-and-matchings-flow) of [Output 26.2](#out-b2-flows-and-matchings-flow): a maximum [flow](#def-b2-flows-and-matchings-flow) is not unique, its [value](#def-b2-flows-and-matchings-flow) is.

**Exercise 26.6 ★★.**

In `exo_match_bug.py`, the marks of the search are created once for all the left vertices instead of once per vertex. On the readers of [Output 26.4](#out-b2-flows-and-matchings-matching) it matches 3 instead of 5. Follow the run and explain which augmenting path it misses.

**Solution of Exercise 26.6.**

```
$ python exo_match_bug.py
one set of marks: 3 [('Ada', 'Mon'), ('Cy', 'Tue'), ('Dee', 'Wed')]
fresh marks     : 5
```

***Output 26.13.** Shared marks against fresh marks.*

Ada takes Monday, which is marked. Ben’s only day is Monday: it is marked, so the search skips it, and Ben stays free, although Ben, Monday, Ada, Tuesday is an augmenting path. Cy takes Tuesday, Dee takes Wednesday, and Eve’s days, Monday and Wednesday, are both marked. A mark means “already tried in this search, without success”; it is valid only during one search, because each augmentation changes the [matching](#def-b2-flows-and-matchings-matching) and opens new [alternating paths](#def-b2-flows-and-matchings-alternating).

**Exercise 26.7 ★★.**

In [Output 26.6](#out-b2-flows-and-matchings-disjoint), find for each pair three roads that separate the two places. Then change the network so that the routes share no place either (other than their ends): split each place into an entrance and an exit joined by an edge of capacity $1$. Compare the numbers given by `exo_vertex_disjoint.py`.

**Solution of Exercise 26.7.**

In all three cases the program’s [cut](#def-b2-flows-and-matchings-cut) is the three roads at one end: the Station’s roads to places 9, 10 and 11, the depot’s roads to places 4, 7 and 24, and the Lighthouse Café’s roads to places 8, 12 and 25. Each of those places has exactly three roads, so three routes is also the obvious upper bound.

```
$ python exo_vertex_disjoint.py
Station to Hospital: 2 routes with no place in common
Bus Depot to Football Ground: 3 routes with no place in common
Lighthouse Café to Town Square: 2 routes with no place in common
```

***Output 26.14.** Routes with no place in common.*

In the split network, a route through a place uses its edge from entrance to exit, of capacity $1$, so routes of a [flow](#def-b2-flows-and-matchings-flow) share no place, and Menger’s theorem becomes: the largest number of routes with no place in common equals the smallest number of places, other than the ends, whose removal separates them. From the Station to the Hospital the number falls to $2$: every route passes the Museum or the Fire Station, which is what the minimum [cut](#def-b2-flows-and-matchings-cut) of the split network names. From the Lighthouse Café to the Town Square the two places are the Museum and the Clinic. From the depot nothing changes.

**Exercise 26.8 ★★.**

Prove [Proposition 26.4](#prop-b2-flows-and-matchings-flow-across-cut).

**Solution of Exercise 26.8.**

Sum, over the vertices $w \in S$, the [flow](#def-b2-flows-and-matchings-flow) out of $w$ less the [flow](#def-b2-flows-and-matchings-flow) into $w$. For $w = s$ the term is $|f|$; for the others it is $0$ by conservation, as $t \notin S$. So the sum is $|f|$. Now group the sum by edges. An edge with both ends in $S$ counts once positively, at its tail, and once negatively, at its head: it cancels. An edge with no end in $S$ does not appear. An edge from $S$ to $T$ appears once positively and an edge from $T$ to $S$ once negatively. What remains is $f(S, T)$.

**Exercise 26.9 ★★.**

Forty readers share a reading room open on 8 slots; reader $k$, for $k = 1$ to $40$, can come at the slots $k \bmod 8$, $3k \bmod 8$ and $(5k + 1) \bmod 8$, once a week. Model the assignment as a [flow](#def-b2-flows-and-matchings-flow). Run `exo_readers.py` with 5 seats per slot, then with the seats $2, 2, 5, 5, 6, 6, 7, 7$, and explain why 40 seats do not place 40 readers.

**Solution of Exercise 26.9.**

[Source](#def-b2-flows-and-matchings-network) to each reader, capacity $1$ (one visit a week); reader to each of their slots, capacity $1$; slot to [sink](#def-b2-flows-and-matchings-network), capacity its number of seats. An integral maximum [flow](#def-b2-flows-and-matchings-flow) places as many readers as possible.

```
$ python exo_readers.py
seats [5, 5, 5, 5, 5, 5, 5, 5], 40 in all: 40 of 40 placed
seats [2, 2, 5, 5, 6, 6, 7, 7], 40 in all: 39 of 40 placed
   readers [8, 16, 24, 32, 40] can only use slots [0, 1], 4 seats
```

***Output 26.15.** The reading room with equal and unequal slots.*

The readers $8, 16, 24, 32, 40$ have $k \equiv 0 \pmod 8$, so $k \bmod 8 = 3k \bmod 8 = 0$ and $(5k + 1) \bmod 8 = 1$: five readers can only come at slots $0$ and $1$, which have $2 + 2 = 4$ seats. Hall’s condition, with seats counted, fails for this set; the total of 40 seats does not help, since the other slots are of no use to these readers.

**Exercise 26.10 ★★★.**

Prove Hall’s theorem directly from the [max-flow](#def-b2-flows-and-matchings-flow) [min-cut](#def-b2-flows-and-matchings-cut) theorem, with the network of [Listing 26.6](#lst-b2-flows-and-matchings-hall): if the maximum [flow](#def-b2-flows-and-matchings-flow) is below $|L|$, show that the vertices of $L$ on the [source](#def-b2-flows-and-matchings-network) side of a minimum [cut](#def-b2-flows-and-matchings-cut) form a set $A$ with $|N(A)| < |A|$.

**Solution of Exercise 26.10.**

The network has capacity $1$ on the edges from $s$ and to $t$, and $|L|$ on the edges from $L$ to $R$. Suppose the maximum [flow](#def-b2-flows-and-matchings-flow) is below $|L|$, and let $(S, T)$ be a minimum [cut](#def-b2-flows-and-matchings-cut): its capacity is below $|L|$, so it contains no edge from $L$ to $R$. Let $A = L \cap S$. A neighbour of a vertex of $A$ is in $S$, else an edge of capacity $|L|$ would cross the [cut](#def-b2-flows-and-matchings-cut): $N(A) \subseteq R \cap S$. The capacity counts the edges $s \to u$ for $u \in L \setminus A$ and $v \to t$ for $v \in
R \cap S$, so

$$
|L| > c(S, T) = |L| - |A| + |R \cap S| \geq |L| - |A| + |N(A)|,
$$

that is $|N(A)| < |A|$. This is what [Listing 26.6](#lst-b2-flows-and-matchings-hall) prints: Ada, Ben and Fay, on the [source](#def-b2-flows-and-matchings-network) side, share Monday and Tuesday. Conversely, if the maximum [flow](#def-b2-flows-and-matchings-flow) is $|L|$, it is a [matching](#def-b2-flows-and-matchings-matching) of all of $L$, and the condition holds.

**Exercise 26.11 ★★★.**

Prove [Lemma 26.12](#lem-b2-flows-and-matchings-monotone). Suppose some distance decreases, choose $v$ of smallest new distance among the vertices whose distance decreased, and look at the last edge $(u, v)$ of a shortest path to $v$ in $G_{f'}$.

**Solution of Exercise 26.11.**

Let $f'$ follow $f$ by augmenting along a shortest path $p$ of $G_f$, and suppose some distance decreases. Among the vertices $v$ with $\delta_{f'}(v) < \delta_f(v)$, choose one with $\delta_{f'}(v)$ smallest; $v \neq s$. Let $u$ be the vertex before $v$ on a shortest path from $s$ to $v$ in $G_{f'}$: $\delta_{f'}(u) = \delta_{f'}(v) - 1$, and by the choice of $v$, $\delta_f(u) \leq \delta_{f'}(u)$.

If $(u, v)$ is an edge of $G_f$, then $\delta_f(v) \leq \delta_f(u) + 1 \leq \delta_{f'}(u) + 1 = \delta_{f'}(v)$, a contradiction. So $(u, v)$ is in $G_{f'}$ but not in $G_f$: the augmentation created it, which means it pushed [flow](#def-b2-flows-and-matchings-flow) from $v$ to $u$, so $(v, u)$ is on $p$. Since $p$ is a shortest path in $G_f$, $\delta_f(u) = \delta_f(v) + 1$. Then

$$
\delta_f(v) = \delta_f(u) - 1 \leq \delta_{f'}(u) - 1 = \delta_{f'}(v) - 2,
$$

again a contradiction. No distance decreases.

**Exercise 26.12 ★★★.**

Let $M$ be a maximum [matching](#def-b2-flows-and-matchings-matching) of a bipartite graph, and $Z$ the set of vertices reachable from the free vertices of $L$ by [alternating paths](#def-b2-flows-and-matchings-alternating) (starting with an edge out of $M$). Prove that $(L \setminus Z) \cup (R \cap Z)$ is a [vertex cover](#def-b2-flows-and-matchings-vertex-cover) of size $|M|$. Implement it, and check it on the readers of [Output 26.5](#out-b2-flows-and-matchings-hall) against all subsets.

**Solution of Exercise 26.12.**

Call $C = (L \setminus Z) \cup (R \cap Z)$.

*$C$ is a cover.* Let $u \in L$, $v \in R$ be joined by an edge. If $u \notin Z$, $u \in C$. If $u \in Z$ and $uv
\notin M$, an [alternating path](#def-b2-flows-and-matchings-alternating) reaching $u$ (empty if $u$ is free, else ending with $u$’s [matching](#def-b2-flows-and-matchings-matching) edge) extends by $uv$, so $v \in Z$ and $v \in C$. If $u \in Z$ and $uv \in M$, then $u$ is matched, so it is not one of the starting vertices, and it was reached through its [matching](#def-b2-flows-and-matchings-matching) edge, from $v$: again $v \in Z$.

*$|C| = |M|$.* Every vertex of $L \setminus Z$ is matched, since the free vertices of $L$ are in $Z$. Every vertex of $R \cap Z$ is matched, otherwise the [alternating path](#def-b2-flows-and-matchings-alternating) reaching it would be augmenting, and $M$ would not be maximum ([Theorem 26.16](#thm-b2-flows-and-matchings-berge)). No edge of $M$ has both ends in $C$: if $v \in R \cap Z$ is matched to $u$, then $u \in Z$. So $v \mapsto$ its [matching](#def-b2-flows-and-matchings-matching) edge is injective on $C$, $|C| \leq |M|$, and $|C| \geq |M|$ for any cover.

```python

def vertex_cover(adj, match):
    """Z: what alternating paths reach from the free left vertices; the cover is the
    left vertices outside Z and the right vertices inside Z."""
    partner = {u: v for v, u in match.items()}
    z_left = [u for u in adj if u not in partner]
    z_right, todo = set(), list(z_left)
    z_left = set(z_left)
    while todo:
        u = todo.pop()
        for v in adj[u]:  # a non-matching edge to the right
            if v not in z_right:
                z_right.add(v)
                w = match.get(v)  # then the matching edge back to the left
                if w is not None and w not in z_left:
                    z_left.add(w)
                    todo.append(w)
    return [u for u in adj if u not in z_left] + sorted(z_right)
```

*The cover read from a maximum [matching](#def-b2-flows-and-matchings-matching) code/bachelor-2/26-flows-and-matchings/listings/exo_cover.py*

```
$ python exo_cover.py
matching of size 5; cover of size 5: ['Cy', 'Dee', 'Eve', 'Mon', 'Tue']
smallest cover by trying all subsets: 5
```

***Output 26.16.** The six readers: a cover of size $5$, and no smaller one.*

## 26.8 Problem: The stadium bus plan

**Problem 26.1.**

Weekend problem — The stadium bus plan

The town plans the buses from the Bus Depot to the Football Ground for a match, with the network of [Listing 26.1](#lst-b2-flows-and-matchings-town). The program below repeats the computation, tries widening each road of the minimum [cut](#def-b2-flows-and-matchings-cut), and assigns drivers to the nine buses.

```python
def plan(widen=None, by=20):
    net, roads = town_network()
    if widen is not None:  # one road made wider, in the direction the cut uses
        net.cap[widen] += by
    value, flow = max_flow(net, DEPOT, GROUND)
    side, cut = min_cut(net, flow, DEPOT)
    return value, cut, net, roads


value, cut, net, roads = plan()
print(f"maximum flow {value} buses an hour = capacity of the minimum cut:")
for e in cut:
    print(f"   road {roads[e]:2}, {PLACES[e[0]]} > {PLACES[e[1]]}: {net.cap[e]}")
for e in cut:
    print(f"widen road {roads[e]:2} by 20: {plan(e)[0]} buses an hour")
value, flow = max_flow(net, DEPOT, GROUND)
near = {GROUND}  # the places that can still reach the ground in the residual network
while grown := {u for u in net.adj for v in near
                if u not in near and net.residual(flow, u, v) > 0}:
    near |= grown
far = sorted((roads[e], c) for e, c in net.cap.items()
             if e[0] not in near and e[1] in near and c > 0)
print("cut nearest the ground: roads", ", ".join(f"{r} ({c})" for r, c in far))
```

***Listing 26.7.** The bus plan: the [flow](#def-b2-flows-and-matchings-flow), the [cut](#def-b2-flows-and-matchings-cut), what widening each road of the [cut](#def-b2-flows-and-matchings-cut) buys, and the [cut](#def-b2-flows-and-matchings-cut) nearest the ground code/bachelor-2/26-flows-and-matchings/listings/bus_plan.py*

```
$ python bus_plan.py
maximum flow 120 buses an hour = capacity of the minimum cut:
   road 16, Hill Park > Market Hall: 40
   road 40, Fire Station > Clinic: 20
   road 11, North School > Football Ground: 20
   road 20, Swimming Pool > Football Ground: 40
widen road 16 by 20: 120 buses an hour
widen road 40 by 20: 120 buses an hour
widen road 11 by 20: 140 buses an hour
widen road 20 by 20: 140 buses an hour
cut nearest the ground: roads 11 (20), 20 (40), 34 (20), 36 (20), 37 (20)
nobody ill, 9 of 9 driven: B1-Bo B2-Hal B3-Ivo B4-Fen B5-Eli B6-Gus B7-Dia B8-Cal B9-Ana
Hal ill, 8 of 9 driven: B1-Bo B2-Eli B3-Ivo B4-Fen B5-Cal B6-Gus B7-Dia B9-Ana
```

***Output 26.8.** 120 buses an hour, two minimum [cuts](#def-b2-flows-and-matchings-cut), and the drivers.*

**Part I — The model.**

1. The town has 30 places and its roads give 105 directed edges. How many roads are one-way, if the table has 53 roads?
2. The rule gives 20, 40 or 60 buses an hour. Which speeds give these, and is 60 used on the routes of [Output 26.1](#out-b2-flows-and-matchings-town) ?
3. Why does a two-way road become two edges of the same capacity, rather than one edge whose capacity is shared by both directions? What would the shared version require?
4. Buses go to the ground and none come back during the hour. Show that a [flow](#def-b2-flows-and-matchings-flow) from the depot to the ground can be chosen with no road used in both directions.
5. The ground has a car park for 100 buses an hour. Add it to the model.
6. What does the [value of a flow](#def-b2-flows-and-matchings-flow) count, in buses, and what does conservation say at the Town Square?

**Part II — Augmenting paths.**

7. The first two paths of [Output 26.1](#out-b2-flows-and-matchings-town) have 2 roads each. Why must breadth-first search find them first?
8. The third path, 16-4-7-23-10-2-11-6-20-15, goes through the North School and then the Swimming Pool. Which edges were full at that point, and why can it not end with 4-15 or 7-15?
9. Check that the path lengths are non-decreasing, and say which result guarantees it.
10. Bound the number of augmentations by [Theorem 26.13](#thm-b2-flows-and-matchings-edmonds-karp-bound) and by [Theorem 26.9](#thm-b2-flows-and-matchings-integrality) . Which bound is better here?
11. Would a depth-first search for augmenting paths reach 120 too? In how many augmentations at most?
12. Give the [flow](#def-b2-flows-and-matchings-flow) at the end on road 11, North School > Football Ground, and on road 20, Swimming Pool > Football Ground, and explain. (Roads are numbered apart from places: the paths print places, the [cuts](#def-b2-flows-and-matchings-cut) print roads.)

**Part III — The bottleneck roads.**

13. Check that the four roads of the first [cut](#def-b2-flows-and-matchings-cut) carry 120 buses an hour between them, and that every route from the depot to the ground uses one of them.
14. Widening road 16, Hill Park > Market Hall, by 20 changes nothing. Why is that not a contradiction with the fact that it belongs to a minimum [cut](#def-b2-flows-and-matchings-cut) ?
15. The program computes a second minimum [cut](#def-b2-flows-and-matchings-cut) , the one nearest the ground. Describe in words how it is computed, and check that its capacity is 120.
16. Prove that a road whose widening raises the maximum [flow](#def-b2-flows-and-matchings-flow) lies in every minimum [cut](#def-b2-flows-and-matchings-cut) , and check it for roads 11 and 20.
17. Is the converse true: does widening a road that lies in every minimum [cut](#def-b2-flows-and-matchings-cut) always raise the maximum [flow](#def-b2-flows-and-matchings-flow) ?
18. State the problem’s result: max [flow](#def-b2-flows-and-matchings-flow) = min [cut](#def-b2-flows-and-matchings-cut) = 120 buses an hour, and the roads in both [cuts](#def-b2-flows-and-matchings-cut) , 11 and 20, are the ones to widen. Widening road 20 by 40 instead of 20 still gives 140 buses an hour: which [cut](#def-b2-flows-and-matchings-cut) limits the [flow](#def-b2-flows-and-matchings-flow) then?

**Part IV — Drivers and buses.**

19. Bus $B_i$ is single-deck, double-deck or electric according to $i \bmod 3$ . List the buses of each kind and the drivers licensed for each.
20. Draw the bipartite graph of drivers and buses, and check the [matching](#def-b2-flows-and-matchings-matching) printed.
21. When Hal is ill, only 8 buses get a driver. Find a set of buses that violates Hall’s condition, on the side of the buses.
22. Find a [vertex cover](#def-b2-flows-and-matchings-vertex-cover) of size 8 of the graph without Hal.
23. Which single driver, added with one licence, would restore 9 buses? Is there more than one answer?
24. Each driver can make two trips in the afternoon and each bus three. Model the assignment of trips as a [flow](#def-b2-flows-and-matchings-flow) .

**Solution of Problem 26.1.**

**1.** A two-way road gives two edges, a one-way road one: $2 \times 52 + 1 = 105$, so one road is one-way (road 1, from the Town Square to the Library).

**2.** $30$, $50$ and $70$ km/h give $20$, $40$ and $60$. Yes: the depot’s road to the South Bridge carries $60$, and so do several roads on the third, fourth and fifth routes.

**3.** The two directions of a road are separate lanes. With a shared capacity, $f(u, v) + f(v, u) \leq c$, the network would be undirected; by question 4 a maximum [flow](#def-b2-flows-and-matchings-flow) never needs both directions, so the shared and the separate models have the same maximum here.

**4.** If $f(u, v) > 0$ and $f(v, u) > 0$, subtract their minimum from both: capacities still hold, every vertex stays balanced and the [value](#def-b2-flows-and-matchings-flow) does not change. The listing does it already, cancelling reverse [flow](#def-b2-flows-and-matchings-flow) before adding.

**5.** Add a vertex for the car park with an edge of capacity $100$ from the ground, and make it the [sink](#def-b2-flows-and-matchings-network). The [cut](#def-b2-flows-and-matchings-cut) that separates it alone has capacity $100$, and the [flow](#def-b2-flows-and-matchings-flow) of $120$ can be reduced to $100$, so the maximum is $100$.

**6.** The number of buses an hour that leave the depot, which is the number arriving at the ground. At the Town Square, as many buses an hour arrive as leave.

**7.** No road joins the depot to the ground, so the shortest routes have two roads, and breadth-first search finds a shortest augmenting path each time; 16-4-15 and 16-7-15 are the two of length 2.

**8.** After the first two, $4 \to 15$ carries $20$ of $20$, $7 \to 15$ and $16 \to 7$ carry $40$ of $40$, and $16 \to 4$ has $20$ left. The path enters by $16 \to 4$ and cannot end with $4 \to 15$ or $7 \to 15$, which are full.

**9.** $2, 2, 9, 10, 14$: by [Lemma 26.12](#lem-b2-flows-and-matchings-monotone) the distance of the ground never decreases, and each path is a shortest path.

**10.** $|V| \cdot |E| = 30 \times 105 = 3150$ against the capacity out of the depot, $40 + 40 + 60 = 140$; the second is much better here, the first does not depend on the capacities.

**11.** Yes: any choice of augmenting paths ends with a maximum [flow](#def-b2-flows-and-matchings-flow) ([Theorem 26.10](#thm-b2-flows-and-matchings-maxflow-mincut)), and with integer capacities each raises the [value](#def-b2-flows-and-matchings-flow) by at least $1$, so at most $120$ augmentations.

**12.** $20$ on road 11 and $40$ on road 20, their capacities: the edges from $S$ to $T$ of the [cut](#def-b2-flows-and-matchings-cut) built from the [residual network](#def-b2-flows-and-matchings-residual) are saturated (proof of [Theorem 26.10](#thm-b2-flows-and-matchings-maxflow-mincut)).

**13.** $40 + 20 + 20 + 40 = 120$. A route starts in $S$ and ends in $T$, so at its first step from $S$ to $T$ it uses an edge from $S$ to $T$, one of the four.

**14.** Road 16 lies in this minimum [cut](#def-b2-flows-and-matchings-cut) but not in the [cut](#def-b2-flows-and-matchings-cut) nearest the ground, whose capacity stays $120$; the [flow](#def-b2-flows-and-matchings-flow) is bounded by every [cut](#def-b2-flows-and-matchings-cut), so it cannot pass $120$. Lying in one minimum [cut](#def-b2-flows-and-matchings-cut) does not make a road a bottleneck.

**15.** It starts from the ground and adds every place from which some place already found can be reached in the [residual network](#def-b2-flows-and-matchings-residual); the [cut](#def-b2-flows-and-matchings-cut) puts these places on the [sink](#def-b2-flows-and-matchings-network) side. Here only the ground itself is found, so the [cut](#def-b2-flows-and-matchings-cut) is the five roads into the ground: $20 + 40 + 20 + 20 + 20 = 120$.

**16.** If a road $e$ is missing from some minimum [cut](#def-b2-flows-and-matchings-cut) $(S, T)$, widening $e$ does not change $c(S, T)$, which still bounds the [flow](#def-b2-flows-and-matchings-flow): the maximum stays the same. Roads 11 and 20 are in both [cuts](#def-b2-flows-and-matchings-cut) printed, and widening them gives 140.

**17.** Yes, with integer capacities and a widening of at least $1$: every minimum [cut](#def-b2-flows-and-matchings-cut) grows by the widening, and every other [cut](#def-b2-flows-and-matchings-cut) had capacity at least the minimum plus $1$, so the new minimum, hence the new maximum [flow](#def-b2-flows-and-matchings-flow), is larger.

**18.** The three roads out of the depot, roads 38, 12 and 21, with $60 + 40 + 40 = 140$, the bound of question 10. The result of the problem: max [flow](#def-b2-flows-and-matchings-flow) $=$ min [cut](#def-b2-flows-and-matchings-cut) $= 120$ buses an hour, and the roads in every minimum [cut](#def-b2-flows-and-matchings-cut), 11 and 20, are the ones to widen, by $20$ at most before the depot’s own roads limit the [flow](#def-b2-flows-and-matchings-flow).

**19.** Double-deck ($i \bmod 3 = 1$): $B_1, B_4, B_7$, drivers Bo, Dia, Fen, Hal. Electric ($2$): $B_2, B_5, B_8$, drivers Cal, Eli, Hal. Single-deck ($0$): $B_3, B_6, B_9$, drivers Ana, Bo, Eli, Gus, Ivo.

**20.** Each printed pair has the right licence, and each driver and each bus appear once: a perfect [matching](#def-b2-flows-and-matchings-matching).

**21.** The electric buses $\{B_2, B_5, B_8\}$ have only Cal and Eli as neighbours: three buses, two drivers.

**22.** Cal, Eli and the six buses $B_1, B_3, B_4, B_6, B_7, B_9$: the electric edges end at Cal or Eli, the others at a double-deck or single-deck bus. Its size $8$ equals the [matching](#def-b2-flows-and-matchings-matching), which proves both optimal.

**23.** A new driver with the electric licence: the [matching](#def-b2-flows-and-matchings-matching) becomes Cal, Eli and the new driver on the three electric buses. A driver with another licence only adds edges to buses already in the cover of question 22, which stays a cover of size 8, so the maximum stays 8: the electric licence is the only answer.

**24.** [Source](#def-b2-flows-and-matchings-network) to each driver, capacity $2$; driver to each bus they may drive, capacity $2$; bus to [sink](#def-b2-flows-and-matchings-network), capacity $3$. An integral maximum [flow](#def-b2-flows-and-matchings-flow) gives the number of trips of each driver on each bus.
