Flow Networks
Water through pipes, packets through a network, goods through a supply chain, cars through a city at rush hour: each moves from a source to a destination through channels of limited capacity. How much can get through per unit of time? That is the maximum-flow problem, and the rest of this course solves it. Besides its literal uses, it models problems that look nothing like plumbing: matching students to projects, scheduling with deadlines, segmenting images, deciding which teams are mathematically eliminated from a league. The DSA course introduces it by example. This lesson gives the precise model.
Definitions
A flow network is a directed graph in which every edge has a non-negative capacity . For convenience set when . Two vertices are special: a source and a sink . We assume every vertex lies on some path from to (other vertices could be deleted), and that the network has no antiparallel edges: if then . Self-loops are excluded too.
A flow is a function with two properties:
- Capacity constraint: for all . In particular there is no flow where there is no edge.
- Flow conservation: for every vertex other than and , what flows in flows out:
The value of a flow is the net flow out of the source:
(Here is a value, not an absolute value or a set size.) Usually no edge enters , and the second sum is 0. The maximum-flow problem asks for a flow of maximum value.
Checking a flow
The network below is used throughout the section. The program stores a candidate flow next to the capacities, checks both properties and computes the value. A second candidate violates conservation at one vertex, a third a capacity.
cap = {("S", "A"): 10, ("S", "B"): 7, ("A", "B"): 4, ("A", "C"): 5, ("B", "D"): 9,
("C", "B"): 3, ("C", "T"): 8, ("D", "C"): 4, ("D", "T"): 6}
V = "SABCDT"
def check(flow, s="S", t="T"):
for e, f in flow.items():
if e not in cap:
return f"flow on {e}, which is not an edge"
if not 0 <= f <= cap[e]:
return f"capacity violated on {e[0]}->{e[1]}: {f} > {cap[e]}"
for u in V:
if u in (s, t):
continue
inflow = sum(f for (a, b), f in flow.items() if b == u)
outflow = sum(f for (a, b), f in flow.items() if a == u)
if inflow != outflow:
return f"conservation violated at {u}: in {inflow}, out {outflow}"
value = sum(f for (a, b), f in flow.items() if a == s) - sum(f for (a, b), f in flow.items() if b == s)
return f"valid flow of value {value}"
good = {("S", "A"): 7, ("S", "B"): 5, ("A", "B"): 2, ("A", "C"): 5, ("B", "D"): 7,
("C", "T"): 6, ("D", "C"): 1, ("D", "T"): 6}
leaky = {**good, ("D", "T"): 5}
greedy = {**good, ("A", "C"): 6, ("S", "A"): 8}
print("candidate 1:", check(good))
print("candidate 2:", check(leaky))
print("candidate 3:", check(greedy))
into_t = sum(f for (a, b), f in good.items() if b == "T")
print("flow arriving at T in candidate 1:", into_t)candidate 1: valid flow of value 12
candidate 2: conservation violated at D: in 7, out 6
candidate 3: capacity violated on A->C: 6 > 5
flow arriving at T in candidate 1: 12
The value 12 that leaves is exactly the amount that arrives at . That is no coincidence: conservation at all the other vertices forces it, and the next lesson proves a stronger version, that the net flow across every cut separating from equals . The best flow for this network has value 14, which the animation finds by Edmonds-Karp, the algorithm of a later lesson:
Two modelling conventions
Antiparallel edges. A road network may have a road in each direction between two junctions, so both and are edges. The algorithms of this section assume that does not happen, because they reserve the reverse direction for "undoing" flow. The fix is to split one of the two edges with a new vertex: replace by and , both with capacity . Any flow in one network corresponds to a flow of the same value in the other.
Several sources and sinks. Factories ship to warehouses . Add a supersource with edges of capacity and a supersink with edges of capacity . A maximum flow from to is then a maximum flow of the multi-source problem. If a factory can produce at most units, give capacity instead.
def add_super(cap, sources, sinks, supply=None):
cap = dict(cap)
for s in sources:
cap[("SRC", s)] = supply[s] if supply else float("inf")
for t in sinks:
cap[(t, "SNK")] = float("inf")
return cap
def split_antiparallel(cap):
cap, n = dict(cap), 0
for (u, v) in sorted(cap):
if (v, u) in cap and u < v: # keep (u, v), route (v, u) through a new vertex
n += 1
x = f"X{n}"
c = cap.pop((v, u))
cap[(v, x)] = c
cap[(x, u)] = c
return cap
roads = {("P", "Q"): 5, ("Q", "P"): 3, ("Q", "R"): 4, ("R", "Q"): 4, ("P", "R"): 2}
fixed = split_antiparallel(roads)
print("after splitting:", fixed)
print("antiparallel pairs left:", sum((v, u) in fixed for (u, v) in fixed))
plants = {("F1", "H"): 6, ("F2", "H"): 4, ("F2", "W2"): 3, ("H", "W1"): 7, ("H", "W2"): 5}
net = add_super(plants, ["F1", "F2"], ["W1", "W2"], supply={"F1": 5, "F2": 6})
print("with a supersource and a supersink:")
for e, c in sorted(net.items()):
print(f" {e[0]:>3} -> {e[1]:<3} capacity {c}")after splitting: {('P', 'Q'): 5, ('Q', 'R'): 4, ('P', 'R'): 2, ('Q', 'X1'): 3, ('X1', 'P'): 3, ('R', 'X2'): 4, ('X2', 'Q'): 4}
antiparallel pairs left: 0
with a supersource and a supersink:
F1 -> H capacity 6
F2 -> H capacity 4
F2 -> W2 capacity 3
H -> W1 capacity 7
H -> W2 capacity 5
SRC -> F1 capacity 5
SRC -> F2 capacity 6
W1 -> SNK capacity inf
W2 -> SNK capacity inf
These two transformations let every algorithm assume one source, one sink and no antiparallel edges. The other usual extension, vertex capacities (a junction that can handle at most cars per minute), works the same way: split vertex into and joined by an edge of capacity .
Test yourself
Which two properties define a flow?
- Acyclicity and connectivity
- The capacity constraint and flow conservation at every vertex except the source and the sink
- Integrality and minimality
- Symmetry and transitivity
A network has edges in both directions between and . How is it turned into one without antiparallel edges?
- Delete one of the edges
- Replace by two edges through a new vertex, both with capacity
- Add the capacities into one edge
- It cannot be done
How do you model three factories, each with a production limit, shipping to two warehouses?
- Run the algorithm three times
- Add a supersource with an edge to each factory whose capacity is its limit, and a supersink with infinite-capacity edges from each warehouse
- Merge the factories into one vertex
- Use a minimum spanning tree