Sub topic 14
Modeling Tricks: Super Sources, Undirected Edges, Vertex Capacities
Real problems rarely arrive as a clean directed graph with one source, one sink, and capacities only on edges. A city has several water plants. A road network has two-way streets. A router can only forward so many packets per second, however many cables are plugged into it. The algorithms from earlier chapters only handle the standard form, so you need ways to rewrite these problems into it without changing the answer.
This chapter assumes you know the definition of a feasible flow, the residual graph, and the adjacency-list MaxFlow implementation with paired forward and reverse edges. Each trick below is a graph transformation. You build a new network whose maximum flow equals the answer to the original problem, then run Edmonds-Karp on it unchanged.
Multiple Sources and Multiple Sinks
Suppose flow can start at any of the sources $s1, \dots, sk$ and end at any of the sinks $t1, \dots, tm$. Add two new vertices:
- A super source $S$, with an edge $S \to s_i$ for every original source.
- A super sink $T$, with an edge $t_j \to T$ for every original sink.
Give each new edge a capacity large enough that it never limits the flow, for example one more than the sum of all real capacities. Any flow in the original multi-source problem extends to a flow in the new network: route the amount each $si$ produces along $S \to si$, and do the same at the sinks. The reverse also holds. Delete $S$ and $T$ from a flow in the new network and you get a valid multi-source flow of the same value. The two maximums are therefore equal.
The new edges also let you express supplies and demands. If plant $si$ can produce at most $ai$ units, set the capacity of $S \to si$ to $ai$. If customer $tj$ accepts at most $bj$ units, set the capacity of $tj \to T$ to $bj$.
Undirected Edges
An undirected edge $\{u, v\}$ with capacity $c$ allows up to $c$ units to move in either direction, but not in both at once. Replace it with two directed edges, $u \to v$ and $v \to u$, each with capacity $c$.
That looks like it allows $c$ units in each direction, $2c$ in total. It is still correct, because a flow that uses both directions can always be simplified. Suppose a flow sends $f1$ on $u \to v$ and $f2$ on $v \to u$. Subtract $\min(f1, f2)$ from both. Capacity constraints still hold, since flows only went down. Conservation still holds at $u$ and $v$, since each vertex lost the same amount coming in as going out. The flow value is unchanged. After this cancellation, at most one direction carries flow, and that flow is a valid flow on the undirected edge.
The paired-edge implementation gives you a cheaper version of this trick. Normally add_edge(u, v, c) stores the forward edge with capacity $c$ and its reverse with capacity $0$. For an undirected edge, give the reverse capacity $c$ as well. Each edge then serves as the other's residual partner. Pushing $x$ units from $u$ to $v$ leaves $c - x$ on $u \to v$ and $c + x$ on $v \to u$. That matches the residual graph of the two-edge model: $c$ units of fresh capacity toward $u$ plus $x$ units of cancellation. You store two edge slots instead of four.
Vertex Capacities
Sometimes the limit sits on a vertex: at most $c(v)$ units may pass through $v$. Max-flow algorithms only know about edge capacities, so turn the vertex into an edge. Split $v$ into two vertices:
- $v_{in}$ receives every edge that used to enter $v$.
- $v_{out}$ starts every edge that used to leave $v$.
- One internal edge $v{in} \to v{out}$ has capacity $c(v)$.
The only edge leaving $v{in}$ is the internal edge, and the only edge entering $v{out}$ is the same edge. Every unit of flow that passes through $v$ must therefore cross $v{in} \to v{out}$, so the total through $v$ is at most $c(v)$.
Two details cause bugs:
- The source and sink. If $s$ or $t$ has a vertex capacity, split it too, and use $s{in}$ as the source and $t{out}$ as the sink, or the other way round if you want the limit to apply. If they have no limit, don't split them.
- Vertex numbering. A common scheme maps vertex $v$ to $2v$ (in) and $2v + 1$ (out). Edges are then added as
add_edge(2*u + 1, 2*v, c), from the out-copy of $u$ to the in-copy of $v$. Mixing up in and out silently disconnects the graph and gives a max flow of 0.
A Worked Example Combining All Three
Two sources, A and B, feed two sinks, X and Y. Both sources can produce any amount. A pumping station M sits in the middle and can handle at most 5 units. There is also a two-way pipe of capacity 2 between B and Y.
| Original element | Capacity | Transformation |
|---|---|---|
| Sources A, B | unlimited | super source S, edges S→A and S→B with "infinite" capacity |
| Sinks X, Y | unlimited | super sink T, edges X→T and Y→T with "infinite" capacity |
| Vertex M | 5 | split into M_in → M_out with capacity 5 |
| A→M, B→M | 4, 6 | A→M_in, B→M_in |
| M→X, M→Y | 7, 3 | M_out→X, M_out→Y |
| B—Y (undirected) | 2 | one paired edge with capacity 2 in both slots |
The code below is self-contained. Its MaxFlow class is the paired-edge implementation from the earlier chapter, with an optional reverse_cap argument added for undirected edges.
from collections import deque
class MaxFlow:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
self.to = []
self.cap = []
def add_edge(self, u, v, c, reverse_cap=0):
# reverse_cap = c makes the edge undirected
self.graph[u].append(len(self.to))
self.to.append(v)
self.cap.append(c)
self.graph[v].append(len(self.to))
self.to.append(u)
self.cap.append(reverse_cap)
def max_flow(self, s, t):
flow = 0
while True:
parent_edge = [-1] * self.n
visited = [False] * self.n
visited[s] = True
queue = deque([s])
while queue and not visited[t]:
u = queue.popleft()
for e in self.graph[u]:
v = self.to[e]
if not visited[v] and self.cap[e] > 0:
visited[v] = True
parent_edge[v] = e
queue.append(v)
if not visited[t]:
return flow
bottleneck = float('inf')
v = t
while v != s:
e = parent_edge[v]
bottleneck = min(bottleneck, self.cap[e])
v = self.to[e ^ 1]
v = t
while v != s:
e = parent_edge[v]
self.cap[e] -= bottleneck
self.cap[e ^ 1] += bottleneck
v = self.to[e ^ 1]
flow += bottleneck
def pumping_network(limit_m):
S, A, B, M_IN, M_OUT, X, Y, T = range(8)
INF = 4 + 6 + 5 + 7 + 3 + 2 + 1 # more than any cut can hold
mf = MaxFlow(8)
mf.add_edge(S, A, INF) # super source
mf.add_edge(S, B, INF)
mf.add_edge(A, M_IN, 4)
mf.add_edge(B, M_IN, 6)
mf.add_edge(M_IN, M_OUT, 5 if limit_m else INF) # vertex capacity
mf.add_edge(M_OUT, X, 7)
mf.add_edge(M_OUT, Y, 3)
mf.add_edge(B, Y, 2, reverse_cap=2) # undirected pipe
mf.add_edge(X, T, INF) # super sink
mf.add_edge(Y, T, INF)
return mf.max_flow(S, T)
print(pumping_network(limit_m=True)) # 7
print(pumping_network(limit_m=False)) # 12With the station limit in place, 5 units pass through M and 2 more go straight from B to Y, for a total of 7. Without the limit, M can pass all 10 units it receives (4 + 6) and send them out on edges with room for 10 (7 + 3). That gives 10 + 2 = 12. The minimum cut confirms the first answer: cutting $M{in} \to M{out}$ (5) and $B \to Y$ (2) separates S from T at cost 7.
Edge Cases and Gotchas
- Antiparallel edges. If the input has both $u \to v$ and $v \to u$, the adjacency-matrix code merges each one's residual capacity with the other's reverse capacity. The max flow value comes out right, but you can no longer read the flow on each edge from the matrix alone. Paired edges keep the two edges separate, so prefer them whenever you need the per-edge flow.
- Parallel edges. Paired edges handle them directly. In a matrix, add their capacities together.
- Edge-disjoint and vertex-disjoint paths. Give every edge capacity 1 and the max flow counts edge-disjoint s-t paths. To count vertex-disjoint paths, also split every vertex other than $s$ and $t$ with internal capacity 1.
- Size growth. Splitting every vertex doubles $V$ and adds $V$ edges. A super source and sink add 2 vertices and $k + m$ edges. Edmonds-Karp's $O(VE^2)$ bound grows accordingly, but only by a constant factor.
Exercise
In the worked example, change the B–Y pipe to a one-way pipe from Y to B with capacity 2, keeping the vertex limit on M. What is the new maximum flow, and why?
Show answer
5. Flow can only enter Y from Mout or from B. With the pipe running Y→B, B can no longer send anything directly to a sink, and any flow into B along Y→B would have to come back through M anyway. Every unit must cross Min→Mout, so the cut {Min→M_out} of capacity 5 is now a minimum cut.
Exercise
You need the maximum number of paths from s to t in a directed graph such that no two paths share a vertex other than s and t. Describe the network you build.
Show answer
Split every vertex v other than s and t into vin and vout with an edge vin→vout of capacity 1. Replace each original edge u→v with uout→vin of capacity 1, treating s as its own out-copy and t as its own in-copy. The maximum s-t flow equals the number of vertex-disjoint paths. By the integrality theorem, the flow is 0 or 1 on every edge, so it splits into that many paths.
Exercise
Three warehouses hold 10, 4, and 7 units. Two stores can accept at most 8 and 12 units. How do you encode these limits, and what is an upper bound on the maximum flow that you can read off without running any algorithm?
Show answer
Add a super source S with edges to the warehouses of capacity 10, 4, and 7, and a super sink T with edges from the stores of capacity 8 and 12. The cut around S has capacity 21 and the cut around T has capacity 20, so the maximum flow is at most 20.