本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
26Flows 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 km/h carries 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:
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)]}")
$ 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
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 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 with two distinct vertices, the source and the sink , and a capacity for each edge . We set when is not an edge.
Definition 26.2 (Flow, value)
A flow is a function on the edges with
- capacity: for every edge;
- conservation: for every vertex , what enters equals what leaves, .
Its value is what leaves the source, less what enters it: . A maximum flow is a flow of largest value.
In Output 26.1 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 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
Definition 26.3 (Cut of a flow network, capacity)
A cut of a flow network is a partition of into two sets and with and . Its capacity is , the capacities of the edges from to only. The net flow across it is .
The cut of a flow network is the cut of a graph of the Year 1 volume with a side chosen for and one for , and it counts only the edges that go forwards, from to .
Proposition 26.4 (Flow across a cut)
Proof. Exercise 26.8: sum the conservation equations over the vertices of other than . ∎
Corollary 26.5 (Weak duality)
For every flow and every cut , . So if , the flow is maximum and the cut is of minimum capacity.
Proof. : the edges from to only subtract, and each edge from to carries at most its capacity. If , then any flow has , and any cut has . ∎
A cut is therefore a certificate: whoever finds a flow and a cut of the same value has proved that both are optimal, and anyone can check it by adding numbers, as the last lines of Output 26.2 do.
26.2 Residual networks and augmenting paths
A first idea is greedy: find a path from to whose edges are not full, push as much as it allows, and repeat. On the network above, the greedy idea can push along and along , and then stops: and are full, and the only remaining path, , uses the full edge . Its value, , is not the maximum. The way out is to allow taking back flow already sent: of the units on can go through instead, which frees for units coming from .
Definition 26.6 (Residual network, augmenting path)
Given a flow , the residual capacity of a pair of vertices is
what can still be pushed from to : the unused capacity of , plus the flow on that can be cancelled. The residual network has an edge whenever . An augmenting path is a path from to in .
Method 26.7 (Ford–Fulkerson)
Start from the zero flow. While the residual network has an augmenting path : let , its bottleneck; for each edge of , first cancel up to units of , then add the rest to . When no augmenting path is left, return .
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)
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}
Lemma 26.8 (Augmenting keeps a flow)
If is a flow and an augmenting path of bottleneck , the result of the augmentation is a flow of value .
Proof. On an edge of , . The listing removes from , which stays , and adds to ; if then and , so the capacity holds. The change makes the net flow from to grow by exactly . At an inner vertex of , the net flow from its predecessor to and from to its successor both grow by , so stays balanced. The path leaves once and never returns to it (a path repeats no vertex), so the net flow out of , , grows by . ∎
Theorem 26.9 (Termination and integrality)
If all capacities are integers, Ford–Fulkerson stops after at most augmentations, whatever the augmenting paths chosen, and returns a flow whose values are all integers. In particular, a network with integer capacities has a maximum flow with integer values.
Proof. By induction, the flow stays integral: the residual capacities of an integral flow are integers, so is the bottleneck , and each augmentation adds or subtracts . Then , and by Lemma 26.8 each augmentation raises the value by at least . The value never exceeds the capacity of the cut (Corollary 26.5), so there are at most augmentations. The 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 the following are equivalent:
- is a maximum flow;
- the residual network has no augmenting path;
- for some cut .
So the value of a maximum flow equals the capacity of a minimum cut, and when no augmenting path is left, the vertices reachable from in form the source side of a minimum cut.
Proof. (1)(2): an augmenting path would give a flow of larger value, by Lemma 26.8.
(2)(3): let be the set of vertices reachable from in , and . Then , and since there is no augmenting path. For and , , otherwise would be reachable. As is a sum of two non-negative terms, and . Every edge from to is saturated and every edge from to empty, so by Proposition 26.4, .
(3)(1): Corollary 26.5. ∎
The function min_cut below is the proof of (2)(3) turned into code: a search in the residual network from , then the edges that leave what it reached.
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)
In Output 26.1 the 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; 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 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 or can push only , through the middle edge or back against it.
$ 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
The listing bad_example.py picks, among all augmenting paths, one of smallest bottleneck, the worst possible choice. With capacities written on bits, 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. It is the default of Listing 26.3.
Write for the distance from to in , in number of edges ( if is unreachable).
Lemma 26.12 (Distances never decrease)
In Edmonds–Karp, if is the flow after an augmentation of , then for every vertex .
Proof. Exercise 26.11. ∎
The paths of Output 26.1 illustrate it: their lengths are 2, 2, 9, 10 and 14 roads.
Theorem 26.13 (Edmonds–Karp bound)
Edmonds–Karp makes at most augmentations, and runs in time , whatever the capacities.
Proof. Call an edge of an augmenting path critical if its residual capacity equals the bottleneck; each augmentation has one, and removes it from the residual network. Since the path is a shortest path, . For to be critical again, it must first come back into the residual network, which happens only when a later augmentation, with flow , uses ; then . By Lemma 26.12, , so
Between two times is critical, the distance of grows by at least . It starts at and stays at most while is on an augmenting path, so is critical at most times. The residual network has at most possible edges, so there are at most augmentations. Each costs one breadth-first search and one pass over the path, when every vertex has an edge, which gives . ∎
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 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 min-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 problem.
Definition 26.14 (Matching)
A matching of an undirected graph is a set of edges no two of which share an end. A vertex is matched if it is an end of an edge of , free otherwise. A maximum matching has as many edges as possible; a perfect matching matches every vertex.
For a bipartite graph with sides and , add a source with an edge of capacity to every vertex of , a sink with an edge of capacity from every vertex of , and direct the edges from to with capacity . By Theorem 26.9 there is a maximum flow with values in ; its edges with flow between and form a matching, since each receives at most and each sends at most . Conversely, a matching gives a flow of the same value. A maximum matching is a maximum flow.
The flow formulation can be specialised. In the residual network, a path from goes to a free vertex of , then alternates: forwards along an edge not in the matching, backwards along an edge of the matching, and ends at a free vertex of .
Definition 26.15 (Alternating and augmenting paths)
Relative to a matching , an alternating path is a path whose edges are alternately out of and in . An augmenting path is an alternating path whose two ends are free.
An augmenting path has one more edge out of than in it. Exchanging them, that is, replacing by the symmetric difference , gives a matching with one more edge.
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
$ 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
Theorem 26.16 (Berge)
A matching is maximum if and only if there is no augmenting path relative to .
Proof. If there is an augmenting path , then is a larger matching. Conversely, suppose is not maximum and let be a larger matching. In the graph with edges , every vertex has degree at most , one edge of each matching; its connected components are therefore paths and cycles whose edges alternate between and . A cycle that alternates has as many edges of each. Since , some path has more edges of than of ; it starts and ends with an edge of , and its ends are free in (an end matched in would have its -edge in the component). It is an augmenting path relative to . ∎
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 . 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 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 of vertices such that every edge has at least one end in .
Every vertex cover has at least as many vertices as any matching has edges, since the edges of a 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 and the smallest vertex cover have the same size.
Proof. Take the network of matchings, but with capacity on the edges from to ; integral flows are still matchings, so the maximum flow is the size of a maximum matching. Let be a minimum cut; its capacity is , at most (the cut has capacity ), so no edge from to goes from to . Its capacity counts the edges with and with , so . The set is a vertex cover: an edge with neither end in would have and , an edge from to across the cut. So the smallest vertex cover has at most vertices, and at least by the remark above. ∎
Exercise 26.12 builds the cover from a maximum matching directly, with alternating paths.
Theorem 26.19 (Hall)
A bipartite graph with sides and has a matching that matches every vertex of if and only if every set has at least neighbours: .
Proof. If such a matching exists, the partners of the vertices of are distinct neighbours. Conversely, suppose no matching matches all of . By Kőnig’s theorem there is a vertex cover with . Let . Every edge from a vertex of must be covered by its other end, so , and
∎
Hall’s condition is checked set by set, and there are sets. The flow finds a violating set without trying them: the readers on the source side of a minimum cut (Exercise 26.10).
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}")
$ python hall.py
6 readers, 5 slots, at most 5 matched
the readers ['Ada', 'Ben', 'Fay'] accept only the 2 slots ['Mon', 'Tue']
26.6 Problems modelled as flows
Much of the use of maximum flows is in reductions: a problem that mentions no flow is turned into a network whose maximum flow or minimum 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 from if every path from to uses one of them.
Theorem 26.21 (Menger)
In a directed graph, the largest number of edge-disjoint paths from to equals the smallest number of edges that separate from .
Proof. Give every edge capacity . Edge-disjoint paths carry together a flow of value their number, so the largest number of paths is at most the maximum flow. Conversely, take an integral maximum flow, of value , with values in . From , follow edges of flow : conservation lets the walk leave every vertex it enters, until it reaches ; if it comes back to a vertex, drop the loop. Removing the flow on this path gives a flow of value ; repeating gives edge-disjoint paths. So the largest number of paths is the maximum flow. A minimum cut has capacity the number of its edges from to , and these separate from ; conversely, the vertices still reachable from after removing a separating set form a cut whose edges from to are all in . So the smallest separating set is a minimum cut, and Theorem 26.10 concludes. ∎
For roads that can be travelled both ways, each road becomes two opposite edges of capacity ; a maximum 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
Assignment with capacities. When the reading room has several seats a day, the edge from a day to the sink gets the number of seats as capacity, and the flow places as many readers as possible; a reader who can come only once a week keeps an edge of capacity from the source (Exercise 26.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 to each project, of capacity its profit; an edge from each piece of equipment to , of capacity its cost; and an edge of very large capacity from each project to each piece of equipment it needs. A cut of finite capacity whose source 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 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
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 min-cut theorem of 1956 contains them all.
26.7 Exercises
Exercise 26.1 ★
On the network of Output 26.2, which of the following are flows, and of which value? : , , , , , , ; : , , , , , , ; : , , , , , , . Check with exo_is_flow.py.
Solution
Solution of Exercise 26.1.
respects the capacities but not conservation at : enter and leave. is balanced but puts on , whose capacity is ; its value would also exceed the cut of capacity . is a flow: at , ; at , ; at , ; at , ; its value is .
$ 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
Exercise 26.2 ★
In exo_no_reverse.py, a network whose residual capacity is only the unused capacity of each edge is given to the same algorithm. What value does it find on the network of Output 26.2, and why? Which line of Listing 26.2 does it miss?
Solution
Solution of Exercise 26.2.
$ python exo_no_reverse.py
Network 12: sact, sadt, sbcadt
Forward 8: sact, sadt
Without reverse edges the search finds and , then stops at : every remaining path to needs , which is full, or entered from , which can no longer feed. The flow needs the path , which sends units back against . The version misses the term of the residual capacity, at the end of line 21 of Listing 26.2.
Exercise 26.3 ★
Find a maximum flow and a minimum cut by hand for the network with edges (9), (7), (3), (4), (6), (2), (5), (7). Then check with exo_maxflow.py.
Solution
Solution of Exercise 26.3.
The shortest paths (bottleneck , at ) and (bottleneck , at ) give . The vertices reachable from afterwards are , and : still has room, but and are full. The cut has capacity ; the edge goes from to 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']
Exercise 26.4 ★
In the bad example, show that the augmenting paths and , taken alternately, take exactly augmentations, and that breadth-first search takes . Compare with Output 26.3.
Solution
Solution of Exercise 26.4.
After the middle edge is full and its residual is backwards; then uses it backwards, cancels the unit, and leaves the middle edge empty again. Each such pair raises the flow on each of the four outer edges by , and each path has bottleneck , so it takes augmentations to reach , as long as no outer edge is full. Breadth-first search finds the two paths of two edges first, each of bottleneck , and then has no residual edge left: augmentations.
Exercise 26.5 ★★
Take the flow of Exercise 26.1. Compute its residual network, the vertices reachable from , and deduce without any further computation that is maximum. Check with exo_mincut.py.
Solution
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
From , only has room (); from , the flow on leaves ; from , the units on can be cancelled, which reaches . The edges and are full, and is full forwards. So , and the cut has capacity . By Corollary 26.5, is maximum. It is not the flow of Output 26.2: a maximum flow is not unique, its value 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 it matches 3 instead of 5. Follow the run and explain which augmenting path it misses.
Solution
Solution of Exercise 26.6.
$ python exo_match_bug.py
one set of marks: 3 [('Ada', 'Mon'), ('Cy', 'Tue'), ('Dee', 'Wed')]
fresh marks : 5
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 and opens new alternating paths.
Exercise 26.7 ★★
In Output 26.6, 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 . Compare the numbers given by exo_vertex_disjoint.py.
Solution
Solution of Exercise 26.7.
In all three cases the program’s 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
In the split network, a route through a place uses its edge from entrance to exit, of capacity , so routes of a 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 : every route passes the Museum or the Fire Station, which is what the minimum 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.
Solution
Solution of Exercise 26.8.
Sum, over the vertices , the flow out of less the flow into . For the term is ; for the others it is by conservation, as . So the sum is . Now group the sum by edges. An edge with both ends in counts once positively, at its tail, and once negatively, at its head: it cancels. An edge with no end in does not appear. An edge from to appears once positively and an edge from to once negatively. What remains is .
Exercise 26.9 ★★
Forty readers share a reading room open on 8 slots; reader , for to , can come at the slots , and , once a week. Model the assignment as a flow. Run exo_readers.py with 5 seats per slot, then with the seats , and explain why 40 seats do not place 40 readers.
Solution
Solution of Exercise 26.9.
Source to each reader, capacity (one visit a week); reader to each of their slots, capacity ; slot to sink, capacity its number of seats. An integral maximum 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
The readers have , so and : five readers can only come at slots and , which have 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 min-cut theorem, with the network of Listing 26.6: if the maximum flow is below , show that the vertices of on the source side of a minimum cut form a set with .
Solution
Solution of Exercise 26.10.
The network has capacity on the edges from and to , and on the edges from to . Suppose the maximum flow is below , and let be a minimum cut: its capacity is below , so it contains no edge from to . Let . A neighbour of a vertex of is in , else an edge of capacity would cross the cut: . The capacity counts the edges for and for , so
that is . This is what Listing 26.6 prints: Ada, Ben and Fay, on the source side, share Monday and Tuesday. Conversely, if the maximum flow is , it is a matching of all of , and the condition holds.
Exercise 26.11 ★★★
Prove Lemma 26.12. Suppose some distance decreases, choose of smallest new distance among the vertices whose distance decreased, and look at the last edge of a shortest path to in .
Solution
Solution of Exercise 26.11.
Let follow by augmenting along a shortest path of , and suppose some distance decreases. Among the vertices with , choose one with smallest; . Let be the vertex before on a shortest path from to in : , and by the choice of , .
If is an edge of , then , a contradiction. So is in but not in : the augmentation created it, which means it pushed flow from to , so is on . Since is a shortest path in , . Then
again a contradiction. No distance decreases.
Exercise 26.12 ★★★
Let be a maximum matching of a bipartite graph, and the set of vertices reachable from the free vertices of by alternating paths (starting with an edge out of ). Prove that is a vertex cover of size . Implement it, and check it on the readers of Output 26.5 against all subsets.
Solution
Solution of Exercise 26.12.
Call .
is a cover. Let , be joined by an edge. If , . If and , an alternating path reaching (empty if is free, else ending with ’s matching edge) extends by , so and . If and , then is matched, so it is not one of the starting vertices, and it was reached through its matching edge, from : again .
. Every vertex of is matched, since the free vertices of are in . Every vertex of is matched, otherwise the alternating path reaching it would be augmenting, and would not be maximum (Theorem 26.16). No edge of has both ends in : if is matched to , then . So its matching edge is injective on , , and for any cover.
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)
$ python exo_cover.py
matching of size 5; cover of size 5: ['Cy', 'Dee', 'Eve', 'Mon', 'Tue']
smallest cover by trying all subsets: 5
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. The program below repeats the computation, tries widening each road of the minimum cut, and assigns drivers to the nine buses.
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))
$ 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
Part I — The model.
- The town has 30 places and its roads give 105 directed edges. How many roads are one-way, if the table has 53 roads?
- 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?
- 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?
- Buses go to the ground and none come back during the hour. Show that a flow from the depot to the ground can be chosen with no road used in both directions.
- The ground has a car park for 100 buses an hour. Add it to the model.
- What does the value of a flow count, in buses, and what does conservation say at the Town Square?
Part II — Augmenting paths.
- The first two paths of Output 26.1 have 2 roads each. Why must breadth-first search find them first?
- 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?
- Check that the path lengths are non-decreasing, and say which result guarantees it.
- Bound the number of augmentations by Theorem 26.13 and by Theorem 26.9. Which bound is better here?
- Would a depth-first search for augmenting paths reach 120 too? In how many augmentations at most?
- Give the 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 print roads.)
Part III — The bottleneck roads.
- Check that the four roads of the first cut carry 120 buses an hour between them, and that every route from the depot to the ground uses one of them.
- 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?
- The program computes a second minimum cut, the one nearest the ground. Describe in words how it is computed, and check that its capacity is 120.
- Prove that a road whose widening raises the maximum flow lies in every minimum cut, and check it for roads 11 and 20.
- Is the converse true: does widening a road that lies in every minimum cut always raise the maximum flow?
- State the problem’s result: max flow = min cut = 120 buses an hour, and the roads in both cuts, 11 and 20, are the ones to widen. Widening road 20 by 40 instead of 20 still gives 140 buses an hour: which cut limits the flow then?
Part IV — Drivers and buses.
- Bus is single-deck, double-deck or electric according to . List the buses of each kind and the drivers licensed for each.
- Draw the bipartite graph of drivers and buses, and check the matching printed.
- 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.
- Find a vertex cover of size 8 of the graph without Hal.
- Which single driver, added with one licence, would restore 9 buses? Is there more than one answer?
- Each driver can make two trips in the afternoon and each bus three. Model the assignment of trips as a flow.
Solution
Solution of Problem 26.1.
1. A two-way road gives two edges, a one-way road one: , so one road is one-way (road 1, from the Town Square to the Library).
2. , and km/h give , and . Yes: the depot’s road to the South Bridge carries , 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, , the network would be undirected; by question 4 a maximum flow never needs both directions, so the shared and the separate models have the same maximum here.
4. If and , subtract their minimum from both: capacities still hold, every vertex stays balanced and the value does not change. The listing does it already, cancelling reverse flow before adding.
5. Add a vertex for the car park with an edge of capacity from the ground, and make it the sink. The cut that separates it alone has capacity , and the flow of can be reduced to , so the maximum is .
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, carries of , and carry of , and has left. The path enters by and cannot end with or , which are full.
9. : by Lemma 26.12 the distance of the ground never decreases, and each path is a shortest path.
10. against the capacity out of the depot, ; 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 (Theorem 26.10), and with integer capacities each raises the value by at least , so at most augmentations.
12. on road 11 and on road 20, their capacities: the edges from to of the cut built from the residual network are saturated (proof of Theorem 26.10).
13. . A route starts in and ends in , so at its first step from to it uses an edge from to , one of the four.
14. Road 16 lies in this minimum cut but not in the cut nearest the ground, whose capacity stays ; the flow is bounded by every cut, so it cannot pass . Lying in one minimum 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; the cut puts these places on the sink side. Here only the ground itself is found, so the cut is the five roads into the ground: .
16. If a road is missing from some minimum cut , widening does not change , which still bounds the flow: the maximum stays the same. Roads 11 and 20 are in both cuts printed, and widening them gives 140.
17. Yes, with integer capacities and a widening of at least : every minimum cut grows by the widening, and every other cut had capacity at least the minimum plus , so the new minimum, hence the new maximum flow, is larger.
18. The three roads out of the depot, roads 38, 12 and 21, with , the bound of question 10. The result of the problem: max flow min cut buses an hour, and the roads in every minimum cut, 11 and 20, are the ones to widen, by at most before the depot’s own roads limit the flow.
19. Double-deck (): , drivers Bo, Dia, Fen, Hal. Electric (): , drivers Cal, Eli, Hal. Single-deck (): , 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.
21. The electric buses have only Cal and Eli as neighbours: three buses, two drivers.
22. Cal, Eli and the six buses : the electric edges end at Cal or Eli, the others at a double-deck or single-deck bus. Its size equals the matching, which proves both optimal.
23. A new driver with the electric licence: the 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 to each driver, capacity ; driver to each bus they may drive, capacity ; bus to sink, capacity . An integral maximum flow gives the number of trips of each driver on each bus.