计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本: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 vv km/h carries v−10v - 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:

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 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)G = (V, E) with two distinct vertices, the source ss and the sink tt, and a capacity c(u,v)≥0c(u, v) \geq 0 for each edge (u,v)(u, v). We set c(u,v)=0c(u, v) = 0 when (u,v)(u, v) is not an edge.

Definition 26.2 (Flow, value)

A flow is a function ff on the edges with

  • capacity: 0≤f(u,v)≤c(u,v)0 \leq f(u, v) \leq c(u, v) for every edge;
  • conservation: for every vertex w≠s,tw \neq s, t, what enters equals what leaves, ∑uf(u,w)=∑vf(w,v)\sum_{u} f(u, w) = \sum_{v} f(w, v).

Its value is what leaves the source, less what enters it: ∣f∣=∑vf(s,v)−∑uf(u,s)|f| = \sum_{v} f(s, v) - \sum_{u} f(u, s). 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
Output 26.2. A maximum flow of a network with six vertices, found in three augmentations, and the 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.
The network of Output 26.2 with its maximum flow, each edge labelled flow/capacity; saturated edges are red. The dashed line is the minimum cut: the edges from SS to TT are (a,d)(a, d) and (c,t)(c, t), both saturated, of total capacity 5+7=125 + 7 = 12, the value of the flow.

Definition 26.3 (Cut of a flow network, capacity)

A cut of a flow network is a partition of VV into two sets SS and T=V∖ST = V \setminus S with s∈Ss \in S and t∈Tt \in T. Its capacity is c(S,T)=∑u∈S, v∈Tc(u,v)c(S, T) = \sum_{u \in S,\, v \in T} c(u, v), the capacities of the edges from SS to TT only. The net flow across it is f(S,T)=∑u∈S, v∈Tf(u,v)−∑u∈T, v∈Sf(u,v)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 of a flow network is the cut of a graph of the Year 1 volume with a side chosen for ss and one for tt, and it counts only the edges that go forwards, from SS to TT.

Proposition 26.4 (Flow across a cut)

For every flow ff and every cut (S,T)(S, T), f(S,T)=∣f∣f(S, T) = |f|.

Proof. Exercise 26.8: sum the conservation equations over the vertices of SS other than ss. ∎

Corollary 26.5 (Weak duality)

For every flow ff and every cut (S,T)(S, T), ∣f∣≤c(S,T)|f| \leq c(S, T). So if ∣f∣=c(S,T)|f| = c(S, T), the flow is maximum and the cut is of minimum capacity.

Proof. ∣f∣=f(S,T)≤∑u∈S,v∈Tf(u,v)≤∑u∈S,v∈Tc(u,v)=c(S,T)|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 TT to SS only subtract, and each edge from SS to TT carries at most its capacity. If ∣f∣=c(S,T)|f| = c(S, T), then any flow f′f' has ∣f′∣≤c(S,T)=∣f∣|f'| \leq c(S, T) = |f|, and any cut (S′,T′)(S', T') has c(S′,T′)≥∣f∣=c(S,T)c(S', T') \geq |f| = c(S, T). ∎

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 ss to tt whose edges are not full, push as much as it allows, and repeat. On the network above, the greedy idea can push 77 along s,a,c,ts, a, c, t and 11 along s,a,d,ts, a, d, t, and then stops: s→as \to a and c→tc \to t are full, and the only remaining path, s,b,c,ts, b, c, t, uses the full edge c→tc \to t. Its value, 88, is not the maximum. The way out is to allow taking back flow already sent: 44 of the 77 units on a→ca \to c can go through dd instead, which frees c→tc \to t for 44 units coming from bb.

Definition 26.6 (Residual network, augmenting path)

Given a flow ff, the residual capacity of a pair of vertices is

cf(u,v)=c(u,v)−f(u,v)+f(v,u),c_f(u, v) = c(u, v) - f(u, v) + f(v, u),

what can still be pushed from uu to vv: the unused capacity of (u,v)(u, v), plus the flow on (v,u)(v, u) that can be cancelled. The residual network GfG_f has an edge (u,v)(u, v) whenever cf(u,v)>0c_f(u, v) > 0. An augmenting path is a path from ss to tt in GfG_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.
The residual network after the first two augmentations of Output 26.2 (flow 77 on s,a,c,ts, a, c, t and 11 on s,a,d,ts, a, d, t). Solid edges are unused capacity, dashed ones flow that can be cancelled. The red path s,b,c,a,d,ts, b, c, a, d, t is an augmenting path of bottleneck 44; its edge c→ac \to a cancels 44 units of the flow on a→ca \to c.

Method 26.7 (Ford–Fulkerson)

Start from the zero flow. While the residual network has an augmenting path pp: let δ=min⁡(u,v)∈pcf(u,v)\delta = \min_{(u, v) \in p} c_f(u, v), its bottleneck; for each edge (u,v)(u, v) of pp, first cancel up to δ\delta units of f(v,u)f(v, u), then add the rest to f(u,v)f(u, v). When no augmenting path is left, return ff.

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: capacities, and the residual capacity of a pair for a given flow code/bachelor-2/26-flows-and-matchings/listings/maxflow.py
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 ff is a flow and pp an augmenting path of bottleneck δ\delta, the result f′f' of the augmentation is a flow of value ∣f∣+δ|f| + \delta.

Proof. On an edge (u,v)(u, v) of pp, δ≤cf(u,v)=(c(u,v)−f(u,v))+f(v,u)\delta \leq c_f(u, v) = (c(u, v) - f(u, v)) + f(v, u). The listing removes b=min⁡(δ,f(v,u))b = \min(\delta, f(v, u)) from f(v,u)f(v, u), which stays ≥0\geq 0, and adds δ−b\delta - b to f(u,v)f(u, v); if b<δb < \delta then b=f(v,u)b = f(v, u) and δ−b≤c(u,v)−f(u,v)\delta - b \leq c(u, v) - f(u, v), so the capacity holds. The change makes the net flow from uu to vv grow by exactly δ\delta. At an inner vertex ww of pp, the net flow from its predecessor to ww and from ww to its successor both grow by δ\delta, so ww stays balanced. The path leaves ss once and never returns to it (a path repeats no vertex), so the net flow out of ss, ∣f∣|f|, grows by δ\delta. ∎

Theorem 26.9 (Termination and integrality)

If all capacities are integers, Ford–Fulkerson stops after at most C=∑vc(s,v)C = \sum_{v} c(s, v) 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 δ\delta, and each augmentation adds or subtracts δ\delta. Then δ≥1\delta \geq 1, and by Lemma 26.8 each augmentation raises the value by at least 11. The value never exceeds the capacity CC of the cut ({s},V∖{s})(\{s\}, V \setminus \{s\}) (Corollary 26.5), so there are at most CC 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 ff the following are equivalent:

  1. ff is a maximum flow;
  2. the residual network GfG_f has no augmenting path;
  3. ∣f∣=c(S,T)|f| = c(S, T) for some cut (S,T)(S, T).

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 ss in GfG_f form the source side of a minimum cut.

Proof. (1)⇒\Rightarrow(2): an augmenting path would give a flow of larger value, by Lemma 26.8.

(2)⇒\Rightarrow(3): let SS be the set of vertices reachable from ss in GfG_f, and T=V∖ST = V \setminus S. Then s∈Ss \in S, and t∈Tt \in T since there is no augmenting path. For u∈Su \in S and v∈Tv \in T, cf(u,v)=0c_f(u, v) = 0, otherwise vv would be reachable. As cf(u,v)=(c(u,v)−f(u,v))+f(v,u)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)f(u, v) = c(u, v) and f(v,u)=0f(v, u) = 0. Every edge from SS to TT is saturated and every edge from TT to SS empty, so by Proposition 26.4, ∣f∣=f(S,T)=c(S,T)|f| = f(S, T) = c(S, T).

(3)⇒\Rightarrow(1): Corollary 26.5. ∎

The function min_cut below is the proof of (2)⇒\Rightarrow(3) turned into code: a search in the residual network from ss, 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)
Listing 26.4. The minimum cut read from the residual network of a maximum flow code/bachelor-2/26-flows-and-matchings/listings/maxflow.py

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 s,a,b,ts, a, b, t or s,b,a,ts, b, a, t can push only 11, 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.
The bad example: the maximum flow is 2C2C. Paths through the middle edge, alternately forwards (s,a,b,ts, a, b, t) and backwards (s,b,a,ts, b, a, t, which cancels the unit just sent), push 11 each and take 2C2C augmentations; the two paths of two edges take 22.
$ 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⁡2C\log_2 C bits, 2C2C 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 δf(v)\delta_f(v) for the distance from ss to vv in GfG_f, in number of edges (∞\infty if vv is unreachable).

Lemma 26.12 (Distances never decrease)

In Edmonds–Karp, if f′f' is the flow after an augmentation of ff, then δf′(v)≥δf(v)\delta_{f'}(v) \geq \delta_f(v) for every vertex vv.

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 ∣V∣⋅∣E∣|V| \cdot |E| augmentations, and runs in time O(∣V∣⋅∣E∣2)O(|V| \cdot |E|^2), whatever the capacities.

Proof. Call an edge (u,v)(u, v) 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, δf(v)=δf(u)+1\delta_f(v) = \delta_f(u) + 1. For (u,v)(u, v) to be critical again, it must first come back into the residual network, which happens only when a later augmentation, with flow gg, uses (v,u)(v, u); then δg(u)=δg(v)+1\delta_g(u) = \delta_g(v) + 1. By Lemma 26.12, δg(v)≥δf(v)\delta_g(v) \geq \delta_f(v), so

δg(u)=δg(v)+1≥δf(v)+1=δf(u)+2.\delta_g(u) = \delta_g(v) + 1 \geq \delta_f(v) + 1 = \delta_f(u) + 2.

Between two times (u,v)(u, v) is critical, the distance of uu grows by at least 22. It starts at ≥0\geq 0 and stays at most ∣V∣−2|V| - 2 while uu is on an augmenting path, so (u,v)(u, v) is critical at most ∣V∣/2|V|/2 times. The residual network has at most 2∣E∣2|E| possible edges, so there are at most ∣V∣⋅∣E∣|V| \cdot |E| augmentations. Each costs one breadth-first search and one pass over the path, O(∣E∣)O(|E|) when every vertex has an edge, which gives O(∣V∣⋅∣E∣2)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)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 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 MM of edges no two of which share an end. A vertex is matched if it is an end of an edge of MM, free otherwise. A maximum matching has as many edges as possible; a perfect matching matches every vertex.

For a bipartite graph with sides LL and RR, add a source ss with an edge of capacity 11 to every vertex of LL, a sink tt with an edge of capacity 11 from every vertex of RR, and direct the edges from LL to RR with capacity 11. By Theorem 26.9 there is a maximum flow with values in {0,1}\{0, 1\}; its edges with flow 11 between LL and RR form a matching, since each u∈Lu \in L receives at most 11 and each v∈Rv \in R sends at most 11. 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 ss goes to a free vertex of LL, then alternates: forwards along an edge not in the matching, backwards along an edge of the matching, and ends at a free vertex of RR.

Definition 26.15 (Alternating and augmenting paths)

Relative to a matching MM, an alternating path is a path whose edges are alternately out of MM and in MM. An augmenting path is an alternating path whose two ends are free.

An augmenting path has one more edge out of MM than in it. Exchanging them, that is, replacing MM by the symmetric difference M⊕pM \oplus p, 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
Listing 26.5. Maximum bipartite 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 of five readers with five days, and the same number as a maximum 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.
Before Eve’s turn in Output 26.4: 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.

Theorem 26.16 (Berge)

A matching MM is maximum if and only if there is no augmenting path relative to MM.

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

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∣⋅∣E∣)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 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 CC of vertices such that every edge has at least one end in CC.

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 ∣L∣+1|L| + 1 on the edges from LL to RR; integral flows are still matchings, so the maximum flow is the size ν\nu of a maximum matching. Let (S,T)(S, T) be a minimum cut; its capacity is ν\nu, at most ∣L∣|L| (the cut ({s},V∖{s})(\{s\}, V \setminus \{s\}) has capacity ∣L∣|L|), so no edge from LL to RR goes from SS to TT. Its capacity counts the edges s→us \to u with u∈L∩Tu \in L \cap T and v→tv \to t with v∈R∩Sv \in R \cap S, so ν=∣L∩T∣+∣R∩S∣\nu = |L \cap T| + |R \cap S|. The set C=(L∩T)∪(R∩S)C = (L \cap T) \cup (R \cap S) is a vertex cover: an edge u,vu, v with neither end in CC would have u∈Su \in S and v∈Tv \in T, an edge from LL to RR across the cut. So the smallest vertex cover has at most ν\nu vertices, and at least ν\nu 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 LL and RR has a matching that matches every vertex of LL if and only if every set A⊆LA \subseteq L has at least ∣A∣|A| neighbours: ∣N(A)∣≥∣A∣|N(A)| \geq |A|.

Proof. If such a matching exists, the partners of the vertices of AA are ∣A∣|A| distinct neighbours. Conversely, suppose no matching matches all of LL. By Kőnig’s theorem there is a vertex cover CC with ∣C∣<∣L∣|C| < |L|. Let A=L∖CA = L \setminus C. Every edge from a vertex of AA must be covered by its other end, so N(A)⊆C∩RN(A) \subseteq C \cap R, and

∣N(A)∣≤∣C∩R∣=∣C∣−∣C∩L∣<∣L∣−∣C∩L∣=∣A∣.|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∣2^{|L|} 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}")
Listing 26.6. When a sixth reader makes a perfect matching impossible, the minimum 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 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 tt from ss if every path from ss to tt uses one of them.

Theorem 26.21 (Menger)

In a directed graph, the largest number of edge-disjoint paths from ss to tt equals the smallest number of edges that separate tt from ss.

Proof. Give every edge capacity 11. 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 kk, with values in {0,1}\{0, 1\}. From ss, follow edges of flow 11: conservation lets the walk leave every vertex it enters, until it reaches tt; if it comes back to a vertex, drop the loop. Removing the flow on this path gives a flow of value k−1k - 1; repeating gives kk edge-disjoint paths. So the largest number of paths is the maximum flow. A minimum cut has capacity the number of its edges from SS to TT, and these separate tt from ss; conversely, the vertices still reachable from ss after removing a separating set FF form a cut whose edges from SS to TT are all in FF. 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 11; 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
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 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 11 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 ss to each project, of capacity its profit; an edge from each piece of equipment to tt, 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
Output 26.7. The library’s projects chosen by a minimum 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 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? f1f_1: sa 7sa\,7, sb 5sb\,5, ac 5ac\,5, ad 2ad\,2, bc 5bc\,5, ct 7ct\,7, dt 2dt\,2; f2f_2: sa 8sa\,8, sb 6sb\,6, ac 3ac\,3, ad 5ad\,5, bc 6bc\,6, ct 9ct\,9, dt 5dt\,5; f3f_3: sa 6sa\,6, sb 6sb\,6, ac 1ac\,1, ad 5ad\,5, bc 6bc\,6, ct 7ct\,7, dt 5dt\,5. Check with exo_is_flow.py.

Solution

Solution of Exercise 26.1.

f1f_1 respects the capacities but not conservation at cc: 5+5=105 + 5 = 10 enter and 77 leave. f2f_2 is balanced but puts 99 on c→tc \to t, whose capacity is 77; its value 1414 would also exceed the cut of capacity 1212. f3f_3 is a flow: at aa, 6=1+56 = 1 + 5; at bb, 6=66 = 6; at cc, 1+6=71 + 6 = 7; at dd, 5=55 = 5; its value is 6+6=126 + 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 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
Output 26.10. With and without the reverse residual edges.

Without reverse edges the search finds s,a,c,ts, a, c, t and s,a,d,ts, a, d, t, then stops at 88: every remaining path to tt needs c→tc \to t, which is full, or a→da \to d entered from aa, which s→as \to a can no longer feed. The flow 1212 needs the path s,b,c,a,d,ts, b, c, a, d, t, which sends 44 units back against a→ca \to c. The version misses the term +f(v,u)+ f(v, u) 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 s→xs \to x (9), s→ys \to y (7), x→yx \to y (3), x→zx \to z (4), y→wy \to w (6), z→yz \to y (2), z→tz \to t (5), w→tw \to t (7). Then check with exo_maxflow.py.

Solution

Solution of Exercise 26.3.

The shortest paths s,x,z,ts, x, z, t (bottleneck 44, at x→zx \to z) and s,y,w,ts, y, w, t (bottleneck 66, at y→wy \to w) give 1010. The vertices reachable from ss afterwards are ss, xx and yy: x→yx \to y still has room, but x→zx \to z and y→wy \to w are full. The cut ({s,x,y},{z,w,t})(\{s, x, y\}, \{z, w, t\}) has capacity 4+6=104 + 6 = 10; the edge z→yz \to y goes from TT to SS 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 and cut by program.

Exercise 26.4 ★

In the bad example, show that the augmenting paths s,a,b,ts, a, b, t and s,b,a,ts, b, a, t, taken alternately, take exactly 2C2C augmentations, and that breadth-first search takes 22. Compare with Output 26.3.

Solution

Solution of Exercise 26.4.

After s,a,b,ts, a, b, t the middle edge is full and its residual is 11 backwards; s,b,a,ts, b, a, t 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 11, and each path has bottleneck 11, so it takes 2C2C augmentations to reach 2C2C, as long as no outer edge is full. Breadth-first search finds the two paths of two edges first, each of bottleneck CC, and then ss has no residual edge left: 22 augmentations.

Exercise 26.5 ★★

Take the flow f3f_3 of Exercise 26.1. Compute its residual network, the vertices reachable from ss, and deduce without any further computation that f3f_3 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
Output 26.12. A few residual capacities of f3f_3, and the vertices reachable from ss.

From ss, only s→as \to a has room (22); from aa, the flow 11 on a→ca \to c leaves 66; from cc, the 66 units on b→cb \to c can be cancelled, which reaches bb. The edges a→da \to d and c→tc \to t are full, and b→cb \to c is full forwards. So S={s,a,b,c}S = \{s, a, b, c\}, and the cut (S,{d,t})(S, \{d, t\}) has capacity 5+7=12=∣f3∣5 + 7 = 12 = |f_3|. By Corollary 26.5, f3f_3 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
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 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 11. 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
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 11, 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 22: 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 w∈Sw \in S, the flow out of ww less the flow into ww. For w=sw = s the term is ∣f∣|f|; for the others it is 00 by conservation, as t∉St \notin S. So the sum is ∣f∣|f|. Now group the sum by edges. An edge with both ends in SS counts once positively, at its tail, and once negatively, at its head: it cancels. An edge with no end in SS does not appear. An edge from SS to TT appears once positively and an edge from TT to SS once negatively. What remains is f(S,T)f(S, T).

Exercise 26.9 ★★

Forty readers share a reading room open on 8 slots; reader kk, for k=1k = 1 to 4040, can come at the slots k mod 8k \bmod 8, 3k mod 83k \bmod 8 and (5k+1) mod 8(5k + 1) \bmod 8, once a week. Model the assignment as a flow. Run exo_readers.py with 5 seats per slot, then with the seats 2,2,5,5,6,6,7,72, 2, 5, 5, 6, 6, 7, 7, and explain why 40 seats do not place 40 readers.

Solution

Solution of Exercise 26.9.

Source to each reader, capacity 11 (one visit a week); reader to each of their slots, capacity 11; 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
Output 26.15. The reading room with equal and unequal slots.

The readers 8,16,24,32,408, 16, 24, 32, 40 have k≡0(mod8)k \equiv 0 \pmod 8, so k mod 8=3k mod 8=0k \bmod 8 = 3k \bmod 8 = 0 and (5k+1) mod 8=1(5k + 1) \bmod 8 = 1: five readers can only come at slots 00 and 11, which have 2+2=42 + 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 min-cut theorem, with the network of Listing 26.6: if the maximum flow is below ∣L∣|L|, show that the vertices of LL on the source side of a minimum cut form a set AA with ∣N(A)∣<∣A∣|N(A)| < |A|.

Solution

Solution of Exercise 26.10.

The network has capacity 11 on the edges from ss and to tt, and ∣L∣|L| on the edges from LL to RR. Suppose the maximum flow is below ∣L∣|L|, and let (S,T)(S, T) be a minimum cut: its capacity is below ∣L∣|L|, so it contains no edge from LL to RR. Let A=L∩SA = L \cap S. A neighbour of a vertex of AA is in SS, else an edge of capacity ∣L∣|L| would cross the cut: N(A)⊆R∩SN(A) \subseteq R \cap S. The capacity counts the edges s→us \to u for u∈L∖Au \in L \setminus A and v→tv \to t for v∈R∩Sv \in R \cap S, so

∣L∣>c(S,T)=∣L∣−∣A∣+∣R∩S∣≥∣L∣−∣A∣+∣N(A)∣,|L| > c(S, T) = |L| - |A| + |R \cap S| \geq |L| - |A| + |N(A)|,

that is ∣N(A)∣<∣A∣|N(A)| < |A|. 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 ∣L∣|L|, it is a matching of all of LL, and the condition holds.

Exercise 26.11 ★★★

Prove Lemma 26.12. Suppose some distance decreases, choose vv of smallest new distance among the vertices whose distance decreased, and look at the last edge (u,v)(u, v) of a shortest path to vv in Gf′G_{f'}.

Solution

Solution of Exercise 26.11.

Let f′f' follow ff by augmenting along a shortest path pp of GfG_f, and suppose some distance decreases. Among the vertices vv with δf′(v)<δf(v)\delta_{f'}(v) < \delta_f(v), choose one with δf′(v)\delta_{f'}(v) smallest; v≠sv \neq s. Let uu be the vertex before vv on a shortest path from ss to vv in Gf′G_{f'}: δf′(u)=δf′(v)−1\delta_{f'}(u) = \delta_{f'}(v) - 1, and by the choice of vv, δf(u)≤δf′(u)\delta_f(u) \leq \delta_{f'}(u).

If (u,v)(u, v) is an edge of GfG_f, then δf(v)≤δf(u)+1≤δf′(u)+1=δf′(v)\delta_f(v) \leq \delta_f(u) + 1 \leq \delta_{f'}(u) + 1 = \delta_{f'}(v), a contradiction. So (u,v)(u, v) is in Gf′G_{f'} but not in GfG_f: the augmentation created it, which means it pushed flow from vv to uu, so (v,u)(v, u) is on pp. Since pp is a shortest path in GfG_f, δf(u)=δf(v)+1\delta_f(u) = \delta_f(v) + 1. Then

δf(v)=δf(u)−1≤δf′(u)−1=δf′(v)−2,\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 MM be a maximum matching of a bipartite graph, and ZZ the set of vertices reachable from the free vertices of LL by alternating paths (starting with an edge out of MM). Prove that (L∖Z)∪(R∩Z)(L \setminus Z) \cup (R \cap Z) is a vertex cover of size ∣M∣|M|. Implement it, and check it on the readers of Output 26.5 against all subsets.

Solution

Solution of Exercise 26.12.

Call C=(L∖Z)∪(R∩Z)C = (L \setminus Z) \cup (R \cap Z).

CC is a cover. Let u∈Lu \in L, v∈Rv \in R be joined by an edge. If u∉Zu \notin Z, u∈Cu \in C. If u∈Zu \in Z and uv∉Muv \notin M, an alternating path reaching uu (empty if uu is free, else ending with uu’s matching edge) extends by uvuv, so v∈Zv \in Z and v∈Cv \in C. If u∈Zu \in Z and uv∈Muv \in M, then uu is matched, so it is not one of the starting vertices, and it was reached through its matching edge, from vv: again v∈Zv \in Z.

∣C∣=∣M∣|C| = |M|. Every vertex of L∖ZL \setminus Z is matched, since the free vertices of LL are in ZZ. Every vertex of R∩ZR \cap Z is matched, otherwise the alternating path reaching it would be augmenting, and MM would not be maximum (Theorem 26.16). No edge of MM has both ends in CC: if v∈R∩Zv \in R \cap Z is matched to uu, then u∈Zu \in Z. So v↦v \mapsto its matching edge is injective on CC, ∣C∣≤∣M∣|C| \leq |M|, and ∣C∣≥∣M∣|C| \geq |M| 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)
The cover read from a maximum 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 55, 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. 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))
Listing 26.7. The bus plan: the flow, the cut, what widening each road of the cut buys, and the 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, 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?
  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 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 count, in buses, and what does conservation say at the Town Square?

Part II — Augmenting paths.

  1. The first two paths of Output 26.1 have 2 roads each. Why must breadth-first search find them first?
  2. 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?
  3. Check that the path lengths are non-decreasing, and say which result guarantees it.
  4. Bound the number of augmentations by Theorem 26.13 and by Theorem 26.9. Which bound is better here?
  5. Would a depth-first search for augmenting paths reach 120 too? In how many augmentations at most?
  6. 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.

  1. 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.
  2. 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?
  3. 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.
  4. Prove that a road whose widening raises the maximum flow lies in every minimum cut, and check it for roads 11 and 20.
  5. Is the converse true: does widening a road that lies in every minimum cut always raise the maximum flow?
  6. 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.

  1. Bus BiB_i is single-deck, double-deck or electric according to i mod 3i \bmod 3. List the buses of each kind and the drivers licensed for each.
  2. Draw the bipartite graph of drivers and buses, and check the matching printed.
  3. 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.
  4. Find a vertex cover of size 8 of the graph without Hal.
  5. Which single driver, added with one licence, would restore 9 buses? Is there more than one answer?
  6. 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: 2×52+1=1052 \times 52 + 1 = 105, so one road is one-way (road 1, from the Town Square to the Library).

2. 3030, 5050 and 7070 km/h give 2020, 4040 and 6060. Yes: the depot’s road to the South Bridge carries 6060, 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)≤cf(u, v) + f(v, u) \leq c, 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 f(u,v)>0f(u, v) > 0 and f(v,u)>0f(v, u) > 0, 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 100100 from the ground, and make it the sink. The cut that separates it alone has capacity 100100, and the flow of 120120 can be reduced to 100100, so the maximum is 100100.

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→154 \to 15 carries 2020 of 2020, 7→157 \to 15 and 16→716 \to 7 carry 4040 of 4040, and 16→416 \to 4 has 2020 left. The path enters by 16→416 \to 4 and cannot end with 4→154 \to 15 or 7→157 \to 15, which are full.

9. 2,2,9,10,142, 2, 9, 10, 14: by Lemma 26.12 the distance of the ground never decreases, and each path is a shortest path.

10. ∣V∣⋅∣E∣=30×105=3150|V| \cdot |E| = 30 \times 105 = 3150 against the capacity out of the depot, 40+40+60=14040 + 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 (Theorem 26.10), and with integer capacities each raises the value by at least 11, so at most 120120 augmentations.

12. 2020 on road 11 and 4040 on road 20, their capacities: the edges from SS to TT of the cut built from the residual network are saturated (proof of Theorem 26.10).

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

14. Road 16 lies in this minimum cut but not in the cut nearest the ground, whose capacity stays 120120; the flow is bounded by every cut, so it cannot pass 120120. 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: 20+40+20+20+20=12020 + 40 + 20 + 20 + 20 = 120.

16. If a road ee is missing from some minimum cut (S,T)(S, T), widening ee does not change c(S,T)c(S, T), 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 11: every minimum cut grows by the widening, and every other cut had capacity at least the minimum plus 11, 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 60+40+40=14060 + 40 + 40 = 140, the bound of question 10. The result of the problem: max flow == min cut =120= 120 buses an hour, and the roads in every minimum cut, 11 and 20, are the ones to widen, by 2020 at most before the depot’s own roads limit the flow.

19. Double-deck (i mod 3=1i \bmod 3 = 1): B1,B4,B7B_1, B_4, B_7, drivers Bo, Dia, Fen, Hal. Electric (22): B2,B5,B8B_2, B_5, B_8, drivers Cal, Eli, Hal. Single-deck (00): B3,B6,B9B_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.

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

22. Cal, Eli and the six buses B1,B3,B4,B6,B7,B9B_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 88 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 22; driver to each bus they may drive, capacity 22; bus to sink, capacity 33. An integral maximum flow gives the number of trips of each driver on each bus.

本章定义的术语

在术语表中查看全部 1050 个术语