Module contents
Lesson 22 of 33Advanced 120 min

Matchings, assignment and minimum-cost flow

Matching is a widely applied combinatorial problem: assigning tasks, matching DETR predictions to objects, or doctors to hospitals. Study bipartite augmenting paths and Hopcroft–Karp, assignment with the Hungarian algorithm and duality, minimum-cost flow with successive shortest paths and potentials, Edmonds' blossoms for general graphs, and Gale–Shapley stable matching.

After this lesson you can

  • Prove Berge's theorem and reduce bipartite matching to maximum flow.
  • Implement Hopcroft–Karp and justify its phase count.
  • Solve assignment with the Hungarian algorithm and interpret potentials as dual variables.
  • Implement minimum-cost flow using successive shortest paths and potentials.
  • Implement Gale–Shapley and prove stability and proposer optimality.

Before you start

Motivation: three ways to match

An object detector such as DETR produces a fixed set of N=100N = 100 predictions per image, each with a box and class distribution, and the image has M≪NM \ll N real objects. Computing loss requires deciding which prediction answers for each object; “each object takes its most similar prediction” fails because two objects could claim the same one and no prediction would learn to stay silent. DETR solves an assignment problem at every training step: the minimum-total-cost partial bijection between predictions and objects (see DETR set prediction). The same problem arises assigning drivers to trips, jobs to machines or tracks to detections in multiobject tracking.

Three variants should be separated from the outset, because each has its own algorithm:

  • Cardinality. Only the number of pairs matters: tasks and qualified people, one task per person. Solve with augmenting paths and, faster, Hopcroft–Karp in O(EV)\bigO(E\sqrt{V}).
  • Cost. Every pair is possible but has a cost, and the cheapest perfect matching is sought. This assignment problem is solved by the Hungarian algorithm in O(n3)\bigO(n^3) and is the simplest case of minimum-cost flow.
  • Preferences. Each side ranks the other, with no numerical costs: residents and hospitals, students and schools. Nothing is optimized; seek a stable matching in which no pair would prefer to run away together. Gale and Shapley’s deferred acceptance solves it.

The first two are linear programs with integer solutions, and the lesson is fundamentally a story of duality: each algorithm maintains a certificate (a vertex cover, potentials) proving that no better solution exists. The third has different structure and is interesting for its incentives.

Bipartite matching as flow

Recall from discrete mathematics that a graph matching is a set MM of edges with no shared endpoints, ν(G)\nu(G) is maximum size, and a path is augmenting relative to MM if it alternates edges outside and inside MM and connects two free vertices. Flipping an augmenting path PP, i.e. moving to M△PM \triangle P, adds one edge. Berge’s theorem says this suffices:

The proof, reconstructed step by step in the exercises, examines symmetric difference M△M∗M \triangle M^* with a larger matching: it is a union of alternating paths and cycles, and some component must be an augmenting path. Remember this idea; it powers the whole section.

In a bipartite graph G=(L∪R,E)G = (L \cup R, E), augmenting-path search is exactly Ford–Fulkerson on a residual graph. Build a network with a source ss joined to each u∈Lu \in L with capacity 1, each edge (u,v)∈E(u, v) \in E directed from LL to RR with capacity 1, and each v∈Rv \in R joined to sink tt with capacity 1.

Two observations before accelerating. First, reduction to flow supplies correctness for free (Berge is the unit case of “a flow is maximum iff there is no residual path”). Second, beware “maximum.” A matching is maximal if no edge can be added, and greedily adding edges while possible gives one. It can be half the optimum, but no less: every edge of maximum matching M∗M^* shares an endpoint with some edge of maximal MM (otherwise it could be added), and each edge of MM has two endpoints, each on at most one edge of M∗M^*. Therefore ∣M∗∣≤2∣M∣|M^*| \le 2|M|.

Hopcroft–Karp: many short paths at once

The simple algorithm performs a complete search for every added edge. In 1973, Hopcroft and Karp observed one breadth-first search can serve many augmentations if flipped paths are shortest and disjoint.

This is Dinic applied to the previous unit network: BFS builds the level graph and DFS computes a blocking flow. The same implementation ideas apply: a current-edge pointer per vertex and marking vertices dead when DFS finds no exit, so each edge is examined O(1)\bigO(1) times per phase and the phase costs O(E)\bigO(E).

InteractiveHopcroft–Karp phases
leftrightabcdefg1234567
  • edge of MM
  • layered graph edge
  • augmenting paths (one color each)
  • cover (König)
start
Empty matching. Each phase performs one BFS from all free left vertices simultaneously, followed by DFS to find a maximal set of disjoint shortest augmenting paths, which are flipped at once. This graph needs 3 phases.
Graph
View
Current ∣M∣|M|0
Phase0 of 3
Shortest path·
Lengths by phase1 → 3 → 7
Hopcroft–Karp phases3
One-at-a-time augmentations7
Vertices and edges14 and 14
Each phase has three frames: BFS layers (in layer view, each column is a layer; colored edges belong to the layer graph), shortest disjoint augmenting paths found by DFS, and their simultaneous flipping. At the end König’s vertex cover certifies the maximum. Compare phase lengths (always increasing) and phase count against individual augmentations. Try the ladder: phase one gets stuck in a maximal matching and phase two fixes it with one 11-edge path. In ‘Not perfect’, the maximum leaves free vertices and König’s cover mixes vertices from both sides. Enable editing and remove or add edges: can you remove a phase or require an extra one?

The figure shows lengths increasing strictly: 1→3→71 \to 3 \to 7 in the three-phase graph. This is the key to the bound and follows from two lemmas.

Proof

In H=M△M∗H = M \triangle M^* every vertex has degree at most 2, one per matching, so components are paths and cycles whose edges alternate between MM and M∗M^*. In each component the number of M∗M^* edges minus MM edges is −1-1, 00 or 11, and the sum over components is ∣M∗∖M∣−∣M∖M∗∣=k|M^* \setminus M| - |M \setminus M^*| = k. Thus at least kk components have difference +1+1: paths starting and ending with M∗M^* edges. Their endpoints are free in MM, because if endpoint xx had an edge e∈Me \in M, it would not be in M∗M^* (where xx already uses the path’s last edge) and would be in HH, extending the component. They are augmenting paths and are disjoint as distinct components.

∎
Proof

Let PP augment relative to M′M' and M′′=M′△PM'' = M' \triangle P, with ∣M′′∣=∣M∣+k+1|M''| = |M| + k + 1. By the previous lemma, M△M′′M \triangle M'' contains k+1k + 1 disjoint augmenting paths relative to MM, each with at least ℓ\ell edges, so ∣M△M′′∣≥(k+1)ℓ|M \triangle M''| \ge (k + 1)\ell. Conversely M△M′′=(P1∪⋯∪Pk)△PM \triangle M'' = (P_1 \cup \cdots \cup P_k) \triangle P, whose edge count is kℓ+∣P∣−2∣P∩⋃iPi∣k\ell + |P| - 2|P \cap \bigcup_i P_i|. Combining,

∣P∣≥ℓ+2 ∣P∩⋃iPi∣.|P| \ge \ell + 2\,\Big|P \cap \bigcup_i P_i\Big|.

If PP shares any edge with the PiP_i, we have ∣P∣≥ℓ+2|P| \ge \ell + 2. If it shares no edge, it shares no vertex either: every vertex of a PiP_i is covered in M′M' by an edge of that PiP_i, and PP, alternating relative to M′M' and free only at endpoints, would use that edge when passing through. Then PP is disjoint from the PiP_i and also augmenting relative to MM (which agrees with M′M' outside the PiP_i); maximality means its length cannot be ℓ\ell. Since ∣P∣≥ℓ|P| \ge \ell and every augmenting path has odd length (it starts and ends with unmatched edges), ∣P∣≥ℓ+2|P| \ge \ell + 2.

∎
Proof

By the second lemma, after kk phases the shortest augmenting path has at least 2k+12k + 1 edges. After k=⌈V ⌉k = \lceil\sqrt{V}\,\rceil phases, let M∗M^* be maximum. The first lemma gives ν−∣M∣\nu - |M| disjoint augmenting paths each with at least 2k+2≥2V2k + 2 \ge 2\sqrt{V} vertices, so (ν−∣M∣) 2V≤V(\nu - |M|)\,2\sqrt{V} \le V and ν−∣M∣≤V/2\nu - |M| \le \sqrt{V}/2. Each later augmenting phase increases ∣M∣|M| by at least one, leaving at most V/2\sqrt{V}/2 such phases. Total augmenting phases are at most ⌈V ⌉+V/2<32V+1\lceil\sqrt{V}\,\rceil + \sqrt{V}/2 < \tfrac32\sqrt{V} + 1, and each costs O(E)\bigO(E).

∎

This is a worst-case bound. In the lab, random graphs with thousands of vertices have far fewer than V\sqrt{V} phases, and the real difference from the simple algorithm appears in graphs forcing it to traverse almost the whole graph for every augmentation.

König from minimum cut

A vertex cover is a set CC touching every edge. Since matching edges share no endpoints, each needs a different vertex of CC, and ν(G)≤∣C∣\nu(G) \le |C| always. König’s theorem says equality holds in bipartite graphs, and the flow reduction proves this in three lines while constructing CC.

Give edges u→vu \to v infinite capacity and retain capacity 1 on ss and tt (maximum flow is unchanged because each uu receives at most one unit). After maximum flow, let SS be vertices reachable from ss in the residual and Z=S∖{s}Z = S \setminus \{s\}. No edge u→vu \to v crosses from SS to its complement because its capacity is infinite and it is never saturated. The cut edges are therefore s→us \to u with u∈L∖Zu \in L \setminus Z and v→tv \to t with v∈R∩Zv \in R \cap Z, and

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

is a cover: if edge (u,v)(u, v) has u∈Zu \in Z, then v∈Zv \in Z and v∈Cv \in C; otherwise u∈Cu \in C. Its size is cut capacity, which equals maximum flow, ν(G)\nu(G). In matching terms, ZZ are vertices reachable by alternating paths from free vertices of LL: exactly Hopcroft–Karp’s final BFS, which finds no free vertex of RR. The red squares at the end of the previous figure are that CC.

The assignment problem

Now all pairs are possible and each has a cost. Given matrix C∈Rn×n\mat{C} \in \R^{n\times n}, choose permutation σ\sigma minimizing ∑iciσ(i)\sum_i c_{i\sigma(i)}. As a linear program, with xijx_{ij} the fraction of row ii assigned to column jj:

(P)min⁡x ∑i,jcij xijs.a. ∑jxij=1  ∀i,∑ixij=1  ∀j,xij≥0,(D)max⁡u,v ∑iui+∑jvjs.a. ui+vj≤cij  ∀i,j.\begin{aligned} \textbf{(P)}\quad \min_{x}\ & \sum_{i,j} c_{ij}\,x_{ij} & \text{s.a.}\ & \sum_j x_{ij} = 1\ \ \forall i, \quad \sum_i x_{ij} = 1\ \ \forall j, \quad x_{ij} \ge 0, \\ \textbf{(D)}\quad \max_{u, v}\ & \sum_i u_i + \sum_j v_j & \text{s.a.}\ & u_i + v_j \le c_{ij}\ \ \forall i, j. \end{aligned}

Dual variables uiu_i (one per row) and vjv_j (one per column) are potentials, and cˉij=cij−ui−vj\bar c_{ij} = c_{ij} - u_i - v_j is reduced cost. Weak duality takes one line: for any feasible xx and (u,v)(u, v), ∑cijxij≥∑(ui+vj) xij=∑iui+∑jvj\sum c_{ij}x_{ij} \ge \sum (u_i + v_j)\,x_{ij} = \sum_i u_i + \sum_j v_j, because rows and columns of xx sum to 1. Feasible potentials therefore lower-bound the cost of any assignment.

One issue remains: (P) is a relaxation, and its optimum might in principle be fractional. It is not.

Proof

Let X\mat{X} be doubly stochastic and BB the row-column bipartite graph with edge (i,j)(i, j) for each xij>0x_{ij} > 0. For a set AA of rows, total mass is ∣A∣|A| and all lies in neighboring columns N(A)N(A), each receiving at most 1; hence ∣N(A)∣≥∣A∣|N(A)| \ge |A|. By Hall’s theorem, BB has a perfect matching, i.e. permutation σ\sigma with xiσ(i)>0x_{i\sigma(i)} > 0 for every ii. Let θ=min⁡ixiσ(i)\theta = \min_i x_{i\sigma(i)}. If θ=1\theta = 1, X\mat{X} is the permutation. Otherwise X=θPσ+(1−θ)X′\mat{X} = \theta\mat{P}_\sigma + (1 - \theta)\mat{X}' with X′=(X−θPσ)/(1−θ)\mat{X}' = (\mat{X} - \theta\mat{P}_\sigma)/(1 - \theta) doubly stochastic and at least one more zero entry; by induction on positive entries, X′\mat{X}' is a convex combination of permutations. Since the (P) objective is linear, its minimum over the polytope occurs at a vertex, and vertices are permutations.

∎

Another view is that the constraint matrix is a bipartite graph’s incidence matrix, which is totally unimodular: all vertices of its polytope are integral. With integrality and strong duality, the optimality criterion is complementary slackness:

A permutation σ\sigma is optimal iff feasible potentials exist (cˉij≥0\bar c_{ij} \ge 0 in every cell) with cˉiσ(i)=0\bar c_{i\sigma(i)} = 0 in every selected cell.

Then ∑iciσ(i)=∑i(ui+vσ(i))=∑u+∑v\sum_i c_{i\sigma(i)} = \sum_i (u_i + v_{\sigma(i)}) = \sum u + \sum v: primal and dual agree. Cells with cˉij=0\bar c_{ij} = 0 are tight, and the problem reduces to finding feasible potentials whose tight cells contain a permutation.

The Hungarian algorithm

Step 2 is the heart of the method. Consider each reduced cost: in tree cells (i∈Si \in S, j∈Tj \in T), add δ\delta to uiu_i and subtract it from vjv_j, and cˉij\bar c_{ij} is unchanged, so tree and MM edges remain tight; in S×T‾S \times \overline{T} it drops δ\delta and does not go negative because δ\delta is the minimum there; in S‾×T\overline{S} \times T it rises δ\delta; elsewhere it is unchanged. Feasibility is preserved, at least one new tight cell leaves the tree, and dual value rises δ(∣S∣−∣T∣)=δ\delta(|S| - |T|) = \delta because the tree always has one more row than columns.

InteractiveThe Hungarian algorithm as duality
col 1v = 0col 2v = 0col 3v = 0col 4v = 0col 5v = 0row 1u = 0row 2u = 0row 3u = 0row 4u = 0row 5u = 011991144883399117744662244774488227755998811667755Dual value versus matching costdual: 0cost of M: 0optimum 12
  • tight cell (cˉij=0\bar c_{ij} = 0)
  • matched
  • alternating tree
  • new edge or path
start
All potentials are 0. Since costs are nonnegative, ui+vj≤ciju_i + v_j \le c_{ij} holds in every cell, and ∑u+∑v=0\sum u + \sum v = 0 is a (trivial) lower bound on the optimum. The algorithm inserts rows one at a time.
Matrix
0
Dual value ∑u+∑v\sum u + \sum v0
Cost of MM0
Optimum (brute force)12
Assigned rows0 of 5
δ\delta for this step·
5×5 cost matrix with potentials uiu_i on the left and vjv_j above. Each cell shows cost in large type and reduced cost cˉij\bar c_{ij} in the corner; shaded cells are tight and blue circles are the matching. Orange rows and columns form the alternating tree. Advance step by step: when no tight cell exits the tree, potentials increase δ\delta and one appears (magenta border). The bar compares dual value, which never falls, with partial-matching cost; they agree after each row and at the final optimum. Click a cell and change its cost: when does the optimal assignment change and when only the potentials?

In the figure’s matrix, rows 3, 4 and 5 have their minimum in the same column, 2, and only one can take it. Summing row minima gives 77, a lower bound; the optimum is 1212 with assignment (1,1),(2,3),(3,5),(4,4),(5,2)(1, 1), (2, 3), (3, 5), (4, 4), (5, 2), and the algorithm ends with potentials u=(1,1,4,5,4)u = (1, 1, 4, 5, 4), v=(0,−3,0,0,0)v = (0, -3, 0, 0, 0) summing exactly to 1212. Those ten numbers are the certificate: anyone can check in a minute that ui+vj≤ciju_i + v_j \le c_{ij} in all 25 cells and all five chosen cells are tight, without rerunning the algorithm.

A finer invariant appears in the bar: after each row, MM cost equals dual value. Since free columns retain vj=0v_j = 0 and others only decrease, any other assignment of those rows costs at least ∑i∈filasui+∑jvj\sum_{i \in \text{filas}} u_i + \sum_j v_j, which is MM cost. Thus after kk rows, MM is an optimal assignment of the first kk rows.

Cost. Each row adds at most nn columns to the tree. If each column’s minimum slack relative to the tree is stored, minvj=min⁡i∈Scˉij\text{minv}_j = \min_{i \in S}\bar c_{ij}, each step updates those slacks with the newly entered row and finds their minimum in O(n)\bigO(n). This is O(n2)\bigO(n^2) per row and O(n3)\bigO(n^3) total. Without the slack array, recomputing δ\delta from scratch costs O(n4)\bigO(n^4), the original version’s bound.

In step 1, choosing the least-slack column and growing the tree is exactly Dijkstra from the new row on nonnegative reduced costs. Each row is a shortest augmenting path and potentials are accumulated distances. This view generalizes to any network, the next section.

Minimum-cost flow

Special cases include shortest path (one unit from ss to tt), maximum flow (zero costs and return edge t→st \to s with cost −1-1), assignment (unit capacities) and transportation (warehouses with supply, stores with demand). It is also discrete optimal transport: Wasserstein distance between discrete distributions is the minimum cost of moving mass from one to the other.

Residual graph GfG_f is the maximum-flow residual with costs: edge x→yx \to y with slack costs w(x,y)w(x, y), and its reverse, when carrying flow, costs −w(x,y)-w(x, y) (undoing one unit returns its cost).

Proof

If a negative cycle exists in GfG_f, sending one unit (or the minimum slack) around it gives a cheaper feasible flow. Conversely, if f∗f^* is feasible and cheaper, f∗−ff^* - f (interpreted in GfG_f: increases on forward edges, decreases on reverse edges) is a circulation in GfG_f of cost w(f∗)−w(f)<0w(f^*) - w(f) < 0. Every circulation decomposes into cycles (flow decomposition without sources or sinks), and if the total is negative some cycle is negative. For potential equivalence: without negative cycles, distances π(x)\pi(x) from an auxiliary vertex connected to all at cost 0 are well-defined and satisfy π(y)≤π(x)+w(x,y)\pi(y) \le \pi(x) + w(x, y), which is wπ≥0w_\pi \ge 0; and if wπ≥0w_\pi \ge 0, cycle cost equals the sum of its reduced costs (potentials cancel around the cycle), which is nonnegative.

∎

This is the same shortest-path Johnson reweighting, and potentials are linear-program dual variables: residual condition wπ≥0w_\pi \ge 0 is minimum-cost-flow complementary slackness. For assignment, π\pi of a row is −ui-u_i and π\pi of a column is vjv_j, and wπw_\pi equals cˉij\bar c_{ij}.

Successive shortest paths

The most direct algorithm sends flow from ss to tt always along the cheapest residual path:

  1. Initial potentials: π=0\pi = 0 if all costs are nonnegative; with negative costs (but no negative cycles), π\pi are Bellman–Ford distances from an auxiliary vertex connected to all at cost 0, as in Johnson. In both cases, wπ≥0w_\pi \ge 0 on every edge.
  2. While more flow is needed, compute distances dd from ss in GfG_f with costs wπw_\pi using Dijkstra; stop if tt is unreachable. Otherwise update π(x)+=min⁡(d(x),d(t))\pi(x) \mathrel{+}= \min(d(x), d(t)) at every vertex (unreachable vertices with d=∞d = \infty increase by d(t)d(t)) and push the greatest admissible amount along the shortest path (its bottleneck).
Proof

Assume wπ≥0w_\pi \ge 0 in GfG_f; let dd be distances from ss at those costs (d=∞d = \infty for unreachable vertices), d^(x)=min⁡(d(x),d(t))\hat d(x) = \min(d(x), d(t)) and π′=π+d^\pi' = \pi + \hat d. For each residual edge (x,y)(x, y), triangle inequality d(y)≤d(x)+wπ(x,y)d(y) \le d(x) + w_\pi(x, y) and wπ(x,y)≥0w_\pi(x, y) \ge 0 give

d^(y)≤min⁡(d(x)+wπ(x,y), d(t))≤d^(x)+wπ(x,y),\hat d(y) \le \min\big(d(x) + w_\pi(x, y),\ d(t)\big) \le \hat d(x) + w_\pi(x, y),

that is, wπ′(x,y)=wπ(x,y)+d^(x)−d^(y)≥0w_{\pi'}(x, y) = w_\pi(x, y) + \hat d(x) - \hat d(y) \ge 0. Vertices on the shortest path to tt have d≤d(t)d \le d(t), so on them d^=d\hat d = d and their edges have exactly zero reduced cost. Pushing flow along that path introduces reverse edges whose reduced cost is −0=0-0 = 0; some edges saturate and disappear, and no others appear. Thus wπ′≥0w_{\pi'} \ge 0 in the new residual. By the previous theorem, flow has no negative cycles in its residual and has minimum cost for its value.

∎

Without potentials Dijkstra cannot be used: after the first augmentation reverse edges with negative cost appear, and Dijkstra on negative weights gives incorrect answers. Potentials let us pay for Bellman–Ford once and Dijkstra on all later iterations. With integer capacities each augmentation pushes at least one unit, and cost is O(F⋅Elog⁡V)\bigO(F \cdot E\log V) for flow of value FF: pseudopolynomial. Capacity scaling makes it polynomial, and strongly polynomial algorithms exist (Orlin, 1993), as do cost-scaling algorithms (Goldberg and Tarjan) and network simplex, used by networkx.min_cost_flow; the 2022 almost-linear-time algorithms also solve minimum-cost flow.

A lab detail: successive paths’ unit costs never decrease. This is reasonable because each path is cheapest available, and the function “minimum cost to send FF units” is convex and piecewise linear in FF.

General graphs: blossoms

Everything above uses bipartiteness. On an arbitrary graph, flow reduction fails: edges cannot be oriented from one side to the other, and the linear relaxation is no longer integral. In a triangle, xe=1/2x_e = 1/2 on every edge satisfies “each vertex covered at most once” with value 3/23/2, while ν=1\nu = 1. Alternating search fails too: from a free vertex another can be reached by an even and odd alternating path around an odd cycle, confusing bipartite search, which labels vertices “even” or “odd.”

The supporting lemma (Edmonds, 1965) says MM admits an augmenting path in GG iff M/BM/B admits one in G/BG/B. With it, the algorithm finds each augmenting path in polynomial time. The original version is O(V4)\bigO(V^4), careful implementations reach O(V3)\bigO(V^3), and the Micali–Vazirani algorithm achieves O(EV)\bigO(E\sqrt{V}), the same bound as Hopcroft–Karp. For weights, Edmonds also gave a primal–dual version adding one dual variable per odd vertex set: the general-graph matching polytope needs inequalities ∑e⊆Uxe≤(∣U∣−1)/2\sum_{e \subseteq U} x_e \le (|U| - 1)/2 for every odd-sized UU, exactly those violated by the triangle. “Paths, trees, and flowers” is also the paper where Edmonds proposed identifying an “efficient algorithm” with a “polynomial algorithm.”

In practice, networkx.max_weight_matching implements the weighted version in O(V3)\bigO(V^3), and with maxcardinality=True gives a maximum-cardinality matching and, among those, maximum weight.

Stable matching

We switch worlds. There are nn residents and nn hospitals (one place each); each resident strictly ranks hospitals and each hospital ranks residents. There are no costs to sum.

A blocking pair is a real threat: aa and hh have incentives to break their assignments and agree independently, which disrupted resident markets in the 1940s with ever-earlier offers and forced acceptance. Gale and Shapley proved in 1962 that a stable matching always exists, with an algorithm.

Deferred acceptance. While a resident is free, they propose to the next hospital on their list. The hospital compares the proposal with its provisional resident (if any), keeps its preferred one and rejects the other, who becomes free. Nothing is final until the end: hence the name.

The figure’s example has four residents and four hospitals. Best to worst, A ranks hospitals 1, 4, 3, 2; B ranks 4, 1, 2, 3; C ranks 3, 2, 1, 4; and D ranks 4, 3, 1, 2. Hospitals 1 through 4 rank residents D, A, C, B; B, D, A, C; A, B, C, D; and C, A, D, B.

InteractiveDeferred acceptance
residents and their listshospitals and their lists1432A4123B3214C4312DDACB1BDAC2ABCD3CADB4
  • accepts
  • switches partner
  • rejects
  • declared false list
start
Residents propose: each free proposer approaches the next option on their list; the receiver keeps the best proposal so far (deferred acceptance: nothing is final until the end).
Rank obtainedABCD1234
residents propose13112133
hospitals propose33431111
Choose someone to see whether misrepresenting their list helps with the current proposing side.
Proposers
Preferences
Proposals0 of 6
Stable matchings3 of 24
Proposals when residents propose6
Proposals when hospitals propose4
Four residents (A to D) and four hospitals (1 to 4) with preference lists, best to worst; click a tile to move it up. Play proposals: proposers move down their lists (crossed-out tiles) and receivers only improve. Change the proposing side and compare the table: with example preferences, every resident obtains a partner at least as good when residents propose, and every hospital when hospitals propose. Then choose who lies: can a lie benefit a proposer? A receiver?
Proof

Termination and perfection. Each resident proposes to each hospital at most once. A hospital receiving a proposal stays matched forever (only improving). The algorithm stops once every hospital has received a proposal, because then the nn are matched to nn different residents and no one is free. Before the last proposal, some hospital has received none, so no resident has exhausted their list: each has made at most n−1n - 1 proposals. Total n(n−1)+1n(n - 1) + 1.

Stability. Suppose (a,h)(a, h) blocks result MM: aa prefers hh to M(a)M(a) and hh prefers aa to M(h)M(h). Because aa proposes in order, they proposed to hh before M(a)M(a), and hh rejected them then or later dropped them for someone better. A hospital’s partner only improves, so hh prefers M(h)M(h) to aa. Contradiction.

Optimality. Suppose in some execution a resident is rejected by a valid partner, and consider the first such moment: hh rejects aa (or drops them) for a′a', and stable matching M′M' has M′(a)=hM'(a) = h. Let h′=M′(a′)h' = M'(a'). Until this moment no resident has been rejected by a valid partner, and a′a' proposed to hh after rejection by every hospital ranked above hh; none was valid for a′a', so h′h' is not ahead of hh on their list: a′a' prefers hh to h′h' (they differ because M′(h)=aM'(h) = a). And hh prefers a′a' to a=M′(h)a = M'(h). Then (a′,h)(a', h) blocks M′M', contradiction. Thus no resident is ever rejected by a valid partner and each ends with their first valid partner.

∎

Two consequences appear in the figure’s table. The result is independent of the order in which free residents propose because it is determined: the proposer-optimal stable matching. And it is the worst stable matching for receivers. Suppose in result MM hospital hh has a=M(h)a = M(h) and in another stable matching M′M' has someone worse, a′=M′(h)a' = M'(h). In M′M' resident aa is not with hh (who has a′a'), and hh is their best valid partner, so aa prefers hh to M′(a)M'(a). Since hh prefers aa to a′a', pair (a,h)(a, h) blocks M′M', which was stable. Thus each receiver gets their worst valid partner in MM. With the figure’s initial lists there are three stable matchings; when residents propose, A, C and D get their first choice, and when hospitals propose all four hospitals get theirs.

Incentives

Can anyone benefit by lying about preferences? A proposer never can: truth-telling is a dominant strategy for the proposing side (Dubins and Freedman, 1981; Roth, 1982). Receivers sometimes can. In the figure, with residents proposing, hospital 1 gets second choice A; if it declares D, B, C, A instead of true list D, A, C, B, it swaps A for B as soon as B proposes, and the rejection chain (A displaces D from hospital 4, D moves down the list) ultimately brings it D, its first choice. Result A-4, B-2, C-3, D-1 is one of the three stable matchings for true preferences: lying does not break stability, it shifts the result toward the liar’s preference. Roth (1982) proved no mechanism always producing stable matchings can be strategy-proof for both sides at once.

This is not a curiosity. In 1984 Roth showed the US resident assignment algorithm (NRMP), in use since the 1950s, was equivalent to deferred acceptance with hospitals proposing; in the late 1990s it was redesigned for residents to propose, with extensions for couples seeking places in the same city (Roth and Peranson, 1999). The quota version (a hospital with several places) is the “college admissions” in Gale and Shapley’s title and uses the same algorithm. Roth and Shapley received the 2012 Nobel Prize in Economics for this theory and practice.

Lab 1: matching and assignment from scratch

First, Hopcroft–Karp with iterative DFS and current-edge pointers, and the simple algorithm for comparison. Both count examined edges, a machine-independent work measure.

[ ]Hopcroft–Karp and the simple algorithmBrowser
from collections import deque
import numpy as np
import networkx as nx

def hopcroft_karp(n_izq, n_der, adj):
    """adj[u] = vecinos derechos de u. Devuelve (mi, md, longitudes, aristas):
    mi[u] = v, md[v] = u (o -1), la longitud mínima de cada fase y las aristas examinadas."""
    INF = float("inf")
    mi, md = [-1] * n_izq, [-1] * n_der
    longitudes, aristas = [], 0
    while True:
        # 1) BFS por capas desde todos los vértices libres de la izquierda a la vez
        dist = [INF] * n_izq
        cola = deque(u for u in range(n_izq) if mi[u] == -1)
        for u in cola:
            dist[u] = 0
        corte = INF                          # longitud del camino aumentante más corto
        while cola:
            u = cola.popleft()
            if 2 * dist[u] + 1 > corte:      # más allá de la capa del primer libre de la derecha
                continue
            for v in adj[u]:
                aristas += 1
                w = md[v]
                if w == -1:
                    corte = min(corte, 2 * dist[u] + 1)
                elif dist[w] == INF:
                    dist[w] = dist[u] + 1
                    cola.append(w)
        if corte == INF:                     # sin caminos aumentantes: máximo (Berge)
            return mi, md, longitudes, aristas
        longitudes.append(corte)
        # 2) DFS por el grafo de capas con puntero de arista actual
        ptr = [0] * n_izq
        for raiz in range(n_izq):
            if mi[raiz] != -1:
                continue
            pila = [raiz]
            while pila:
                u = pila[-1]
                if ptr[u] == len(adj[u]):    # callejón sin salida: muerto en esta fase
                    dist[u] = INF
                    pila.pop()
                    if pila:
                        ptr[pila[-1]] += 1
                    continue
                v = adj[u][ptr[u]]
                aristas += 1
                w = md[v]
                if w == -1 and 2 * dist[u] + 1 == corte:
                    for x in pila:           # invertir: cada x toma su arista actual
                        vx = adj[x][ptr[x]]
                        mi[x], md[vx] = vx, x
                    break
                if w != -1 and dist[w] == dist[u] + 1 and 2 * dist[w] < corte:
                    pila.append(w)
                else:
                    ptr[u] += 1

def kuhn(n_izq, n_der, adj):
    """Una búsqueda alternante (DFS iterativa) por vértice de la izquierda."""
    md = [-1] * n_der
    aumentos = aristas = 0
    for s in range(n_izq):
        visto = [False] * n_der
        pila, via, ptr = [s], [], {s: 0}
        while pila:
            u = pila[-1]
            if ptr[u] == len(adj[u]):
                pila.pop()
                if via:
                    via.pop()
                continue
            v = adj[u][ptr[u]]
            ptr[u] += 1
            aristas += 1
            if visto[v]:
                continue
            visto[v] = True
            via.append(v)
            if md[v] == -1:                  # libre: invertir el camino
                for x, y in zip(pila, via):
                    md[y] = x
                aumentos += 1
                break
            pila.append(md[v])
            ptr[md[v]] = 0
    return md, aumentos, aristas

def bipartito_aleatorio(n, grado, semilla):
    rng = np.random.default_rng(semilla)
    us, vs = rng.integers(0, n, n * grado), rng.integers(0, n, n * grado)
    adj = [[] for _ in range(n)]
    for u, v in sorted(set(zip(us.tolist(), vs.tolist()))):
        adj[u].append(v)
    return adj

# corrección contra networkx
for semilla in range(30):
    n = 40
    adj = bipartito_aleatorio(n, 2, semilla)
    mi, md, _, _ = hopcroft_karp(n, n, adj)
    assert all(md[mi[u]] == u for u in range(n) if mi[u] != -1)
    G = nx.Graph([(("i", u), ("d", v)) for u in range(n) for v in adj[u]])
    izq = [x for x in G if x[0] == "i"]
    ref = len(nx.bipartite.hopcroft_karp_matching(G, top_nodes=izq)) // 2
    assert sum(x != -1 for x in mi) == ref == kuhn(n, n, adj)[1]
print("30 grafos aleatorios: Hopcroft-Karp, Kuhn y networkx dan el mismo tamaño\n")

print(f"{'n':>6} {'|E|':>7} {'|M|':>6} {'fases':>6} {'cota':>5}   longitudes por fase")
for n in [250, 1000, 4000]:
    adj = bipartito_aleatorio(n, 3, 1)
    mi, md, L, _ = hopcroft_karp(n, n, adj)
    cota = 1.5 * (2 * n) ** 0.5 + 1                  # la del teorema, con V = 2n
    print(f"{n:>6} {sum(map(len, adj)):>7} {sum(x != -1 for x in mi):>6} {len(L):>6} {cota:>5.0f}   {L}")

Table lengths are 1,3,5,…1, 3, 5, \dots: they increase at least 2 per phase as the lemma says and sometimes jump further. The number of augmenting phases is far below the theorem’s bound 32V+1\tfrac32\sqrt{V} + 1: 23 versus 135 with n=4000n = 4000. Now the work. On a sparse random graph the difference from the simple algorithm is moderate, about three times fewer examined edges, because its searches are usually short. But some graphs force it to traverse almost everything per augmentation: in the “triangular” one, vertex uiu_i connects to v0,…,viv_0, \dots, v_i in that order and each search first tries every occupied column.

[ ]Phases versus augmentations: where it mattersBrowser
import time

def triangular(n):
    return [list(range(i + 1)) for i in range(n)]

casos = [("aleatorio, n = 4000", 4000, bipartito_aleatorio(4000, 3, 1)),
         ("triangular, n = 150", 150, triangular(150))]
for nombre, n, adj in casos:
    E = sum(map(len, adj))
    t = time.perf_counter(); mi, _, L, a_hk = hopcroft_karp(n, n, adj); t_hk = time.perf_counter() - t
    t = time.perf_counter(); md, aum, a_k = kuhn(n, n, adj); t_k = time.perf_counter() - t
    print(f"{nombre}: |E| = {E}")
    print(f"   Hopcroft-Karp: {len(L)} fases, {a_hk} aristas examinadas ({t_hk * 1e3:.0f} ms)")
    print(f"   simple:        {aum} aumentos, {a_k} aristas examinadas ({t_k * 1e3:.0f} ms)")

In the triangular graph, Hopcroft–Karp finishes in one phase (at layer 0 all vertices are free; DFS of uiu_i discards occupied v0,…,vi−1v_0, \dots, v_{i-1} with one check each and takes viv_i, so BFS and DFS each examine ∣E∣|E| edges), while the simple algorithm examines order n3/6n^3/6 edges, Θ(VE)\Theta(VE): about 574 000 versus 22 650. A greedy initial matching would fix this case, which is why real implementations use it; bound O(EV)\bigO(E\sqrt{V}) guarantees the other cases.

König’s certificate comes from the final BFS: vertices reachable by alternating paths from free vertices on the left.

[ ]König vertex coverBrowser
def recubrimiento_konig(n_izq, n_der, adj, mi, md):
    """Z = alcanzables por caminos alternantes desde los libres de L. Devuelve L - Z y R ∩ Z."""
    zi, zd = [False] * n_izq, [False] * n_der
    cola = deque(u for u in range(n_izq) if mi[u] == -1)
    for u in cola:
        zi[u] = True
    while cola:
        u = cola.popleft()
        for v in adj[u]:
            if v != mi[u] and not zd[v]:
                zd[v] = True
                w = md[v]                    # nunca -1: habría un camino aumentante
                if not zi[w]:
                    zi[w] = True
                    cola.append(w)
    return [u for u in range(n_izq) if not zi[u]], [v for v in range(n_der) if zd[v]]

n = 1000
adj = bipartito_aleatorio(n, 2, 7)
mi, md, _, _ = hopcroft_karp(n, n, adj)
CL, CR = recubrimiento_konig(n, n, adj, mi, md)
sL, sR = set(CL), set(CR)
print(f"|M| = {sum(x != -1 for x in mi)},  |C| = {len(CL) + len(CR)}")
print("¿C toca todas las aristas?", all(u in sL or v in sR for u in range(n) for v in adj[u]))

Now the O(n3)\bigO(n^3) Hungarian algorithm from the previous section as written: rows inserted one by one, the minv slack array and way to recover the path. The inner loop is vectorized with NumPy but performs exactly the pseudocode operations.

[ ]Hungarian algorithm with potentialsBrowser
from scipy.optimize import linear_sum_assignment

def hungaro(C):
    """Asignación de coste mínimo de una matriz n x m con n <= m.
    Devuelve (asig, u, v): la fila i va a la columna asig[i]; u, v son los potenciales."""
    C = np.asarray(C, dtype=float)
    n, m = C.shape
    assert n <= m, "si hay más filas que columnas, trasponer"
    u = np.zeros(n + 1)                  # potenciales de filas (el índice 0 es ficticio)
    v = np.zeros(m + 1)                  # potenciales de columnas
    p = np.zeros(m + 1, dtype=int)       # p[j] = fila (desde 1) emparejada con la columna j
    way = np.zeros(m + 1, dtype=int)     # columna anterior en el árbol alternante
    for i in range(1, n + 1):
        p[0] = i                         # la columna ficticia 0 sostiene la fila nueva
        j0 = 0
        minv = np.full(m + 1, np.inf)    # holgura mínima de cada columna respecto del árbol
        usado = np.zeros(m + 1, dtype=bool)
        while True:
            usado[j0] = True
            i0 = p[j0]                   # la fila que acaba de entrar en el árbol
            libres = ~usado
            libres[0] = False
            red = C[i0 - 1] - u[i0] - v[1:]
            mejora = libres[1:] & (red < minv[1:])
            minv[1:][mejora] = red[mejora]
            way[1:][mejora] = j0
            cand = np.where(libres, minv, np.inf)
            j1 = int(np.argmin(cand))
            delta = cand[j1]
            u[p[usado]] += delta         # filas del árbol: suben
            v[usado] -= delta            # columnas del árbol: bajan
            minv[libres] -= delta
            j0 = j1
            if p[j0] == 0:               # columna libre: camino aumentante
                break
        while j0:                        # invertir el camino siguiendo way
            j1 = way[j0]
            p[j0] = p[j1]
            j0 = j1
    asig = np.full(n, -1)
    for j in range(1, m + 1):
        if p[j]:
            asig[p[j] - 1] = j - 1
    return asig, u[1:], v[1:]

C = np.array([[1, 9, 1, 4, 8], [3, 9, 1, 7, 4], [6, 2, 4, 7, 4], [8, 2, 7, 5, 9], [8, 1, 6, 7, 5]])
asig, u, v = hungaro(C)
print("asignación (fila -> columna, desde 1):", asig + 1)
print("coste:", C[np.arange(5), asig].sum(), "  dual:", u.sum() + v.sum(), "  u =", u, "  v =", v)
print("factible:", (C - u[:, None] - v[None, :]).min() >= 0)

rng = np.random.default_rng(0)
peor = 0.0
for _ in range(200):
    n = int(rng.integers(1, 16))
    Cr = rng.integers(0, 100, size=(n, 15)).astype(float)
    a, uu, vv = hungaro(Cr)
    f, c = linear_sum_assignment(Cr)
    peor = max(peor, abs(Cr[np.arange(n), a].sum() - Cr[f, c].sum()))
print("200 matrices, también rectangulares: diferencia máxima con linear_sum_assignment =", peor)

# el mismo óptimo con el emparejamiento de peso máximo de networkx (Edmonds)
Cr = rng.integers(0, 50, size=(8, 8))
B = nx.Graph()
B.add_weighted_edges_from((("f", i), ("c", j), 100 - int(Cr[i, j])) for i in range(8) for j in range(8))
Mx = nx.max_weight_matching(B, maxcardinality=True)
print("networkx.max_weight_matching:", sum(Cr[a[1], b[1]] if a[0] == "f" else Cr[b[1], a[1]] for a, b in Mx),
      "  húngaro:", Cr[np.arange(8), hungaro(Cr)[0]].sum())

for n in [100, 200]:
    Cr = rng.random((n, n))
    t = time.perf_counter(); a, _, _ = hungaro(Cr); t1 = time.perf_counter() - t
    t = time.perf_counter(); f, c = linear_sum_assignment(Cr); t2 = time.perf_counter() - t
    print(f"n = {n}: propio {t1 * 1e3:.0f} ms, scipy {t2 * 1e3:.1f} ms, mismo coste: {np.isclose(Cr[np.arange(n), a].sum(), Cr[f, c].sum())}")

Final potentials are those in the figure, u=(1,1,4,5,4)u = (1, 1, 4, 5, 4) and v=(0,−3,0,0,0)v = (0, -3, 0, 0, 0), and dual value equals cost. SciPy implements a Jonker–Volgenant variant in C++, using the same shortest-augmenting-path scheme; speed difference is implementation, not algorithm.

Minimum-cost flow by successive shortest paths, with forward and reverse edges in consecutive positions (the reverse of e is e ^ 1):

[ ]Minimum-cost flow by successive shortest pathsBrowser
import heapq

class RedCoste:
    def __init__(self, n):
        self.n = n
        self.g = [[] for _ in range(n)]
        self.to, self.cap, self.w = [], [], []

    def arista(self, a, b, cap, w):
        for x, y, c, ww in ((a, b, cap, w), (b, a, 0, -w)):    # directa e inversa
            self.g[x].append(len(self.to))
            self.to.append(y); self.cap.append(c); self.w.append(ww)

    def flujo_coste_min(self, s, t, demanda=float("inf")):
        n, INF = self.n, float("inf")
        # potenciales iniciales: Bellman-Ford desde un vértice auxiliar unido a todos con coste 0
        # (empezar con pi = 0 en todos es su primera ronda; admite costes negativos sin ciclos negativos)
        pi = [0] * n
        for _ in range(n):
            cambio = False
            for x in range(n):
                for e in self.g[x]:
                    if self.cap[e] > 0 and pi[x] + self.w[e] < pi[self.to[e]]:
                        pi[self.to[e]] = pi[x] + self.w[e]
                        cambio = True
            if not cambio:
                break
        flujo = coste = 0
        unitarios = []
        while flujo < demanda:
            # Dijkstra con costes reducidos w + pi[x] - pi[y] >= 0
            d, prev = [INF] * n, [-1] * n
            d[s] = 0
            h = [(0, s)]
            while h:
                dx, x = heapq.heappop(h)
                if dx > d[x]:
                    continue
                for e in self.g[x]:
                    y = self.to[e]
                    if self.cap[e] > 0 and dx + self.w[e] + pi[x] - pi[y] < d[y]:
                        d[y] = dx + self.w[e] + pi[x] - pi[y]
                        prev[y] = e
                        heapq.heappush(h, (d[y], y))
            if d[t] == INF:
                break
            for x in range(n):                       # pi += min(d, d(t)): los no alcanzables suben d(t)
                pi[x] += min(d[x], d[t])
            b, y = demanda - flujo, t                # cuello de botella
            while y != s:
                e = prev[y]; b = min(b, self.cap[e]); y = self.to[e ^ 1]
            y = t
            while y != s:
                e = prev[y]; self.cap[e] -= b; self.cap[e ^ 1] += b; y = self.to[e ^ 1]
            flujo += b
            coste += b * (pi[t] - pi[s])             # coste real del camino
            unitarios.append(pi[t] - pi[s])
        return flujo, coste, unitarios

# transporte: 3 almacenes, 4 tiendas, coste por unidad
oferta, demanda = [20, 30, 25], [10, 25, 15, 25]
W = [[8, 6, 10, 9], [9, 12, 13, 7], [14, 9, 16, 5]]
S, T = 7, 8
red = RedCoste(9)
for a in range(3):
    red.arista(S, a, oferta[a], 0)
for b in range(4):
    red.arista(3 + b, T, demanda[b], 0)
for a in range(3):
    for b in range(4):
        red.arista(a, 3 + b, 10**9, W[a][b])
fl, co, unitarios = red.flujo_coste_min(S, T)
print("flujo:", fl, "  coste mínimo:", co)
print("coste por unidad de cada camino (nunca baja):", unitarios)

G = nx.DiGraph()
for a in range(3):
    G.add_node(f"A{a}", demand=-oferta[a])
for b in range(4):
    G.add_node(f"T{b}", demand=demanda[b])
for a in range(3):
    for b in range(4):
        G.add_edge(f"A{a}", f"T{b}", weight=W[a][b])
print("networkx.min_cost_flow:", nx.cost_of_flow(G, nx.min_cost_flow(G)))

# la asignación es el caso de capacidades unitarias
red = RedCoste(12)
for i in range(5):
    red.arista(10, i, 1, 0)
    red.arista(5 + i, 11, 1, 0)
    for j in range(5):
        red.arista(i, 5 + j, 1, int(C[i, j]))
print("la matriz de 5x5 como flujo de coste mínimo:", red.flujo_coste_min(10, 11)[:2])

Unit cost of the five paths rises, 5,6,9,11,135, 6, 9, 11, 13, and total matches networkx network simplex. The 5×5 assignment as flow gives 5 units at cost 12: each shortest path is one Hungarian row insertion.

For general graphs, networkx includes blossoms. With a triangle and two tails:

[ ]Blossoms: a non-bipartite graphBrowser
Gt = nx.Graph([(1, 2), (2, 3), (3, 1), (1, 4), (3, 5), (5, 6)])
print("emparejamiento máximo (Edmonds):", sorted(tuple(sorted(e)) for e in nx.max_weight_matching(Gt, maxcardinality=True)))
print("¿bipartito?", nx.is_bipartite(Gt))

Finally, deferred acceptance, with brute-force checks of stability and proposer optimality and proposal counts under random preferences.

[ ]Gale–Shapley: stability, optimality and costBrowser
from itertools import permutations

def gale_shapley(P, R):
    """P[i]: lista del proponente i; R[j]: lista del receptor j. Devuelve (m, propuestas), m[i] = j."""
    n = len(P)
    rango = [[0] * n for _ in range(n)]
    for j in range(n):
        for k, i in enumerate(R[j]):
            rango[j][i] = k
    sig, pareja, libres, propuestas = [0] * n, [-1] * n, list(range(n)), 0
    while libres:
        i = libres.pop()
        j = P[i][sig[i]]
        sig[i] += 1
        propuestas += 1
        if pareja[j] == -1:
            pareja[j] = i
        elif rango[j][i] < rango[j][pareja[j]]:
            libres.append(pareja[j])
            pareja[j] = i
        else:
            libres.append(i)
    m = [-1] * n
    for j, i in enumerate(pareja):
        m[i] = j
    return m, propuestas

def es_estable(P, R, m):
    inv = {j: i for i, j in enumerate(m)}
    for i in range(len(P)):
        for j in P[i]:
            if j == m[i]:
                break
            if R[j].index(i) < R[j].index(inv[j]):
                return False
    return True

rng = np.random.default_rng(1)
n, optimo, total = 7, 0, 0
for _ in range(40):
    P = [rng.permutation(n).tolist() for _ in range(n)]
    R = [rng.permutation(n).tolist() for _ in range(n)]
    m, _ = gale_shapley(P, R)
    assert es_estable(P, R, m)
    estables = [mm for mm in permutations(range(n)) if es_estable(P, R, mm)]
    mejor = [min(P[i].index(mm[i]) for mm in estables) for i in range(n)]
    optimo += all(P[i].index(m[i]) == mejor[i] for i in range(n))
    total += len(estables)
print(f"40 instancias con n = {n}: todas estables; óptimo para quien propone en {optimo} de 40;"
      f" {total / 40:.2f} emparejamientos estables de media")

for n in [100, 200, 400]:
    props = [gale_shapley([rng.permutation(n).tolist() for _ in range(n)],
                          [rng.permutation(n).tolist() for _ in range(n)])[1] for _ in range(3)]
    print(f"n = {n}: {np.mean(props):.0f} propuestas de media;  n ln n = {n * np.log(n):.0f};  cota n² − n + 1 = {n * n - n + 1}")

The professional version

ProblemFunctionAlgorithm
Maximum bipartite matchingnetworkx.bipartite.hopcroft_karp_matching(G, top_nodes)Hopcroft–Karp
Same on sparse matrixscipy.sparse.csgraph.maximum_bipartite_matching(A)Hopcroft–Karp in C
Assignment (rectangular, min⁡\min or max⁡\max)scipy.optimize.linear_sum_assignment(C, maximize=False)modified Jonker–Volgenant, O(n3)\bigO(n^3)
Sparse assignmentscipy.sparse.csgraph.min_weight_full_bipartite_matching(A)LAPJVsp
General-graph matchingnetworkx.max_weight_matching(G, maxcardinality)Edmonds’ blossoms, O(V3)\bigO(V^3)
Minimum-cost flow, transportationnetworkx.min_cost_flow(G), networkx.network_simplex(G)network simplex
Large problemsOR-Tools (SimpleMinCostFlow, LinearSumAssignment)cost scaling

Two important linear_sum_assignment details: it accepts rectangular matrices (matching all rows if fewer rows than columns, otherwise all columns) and accepts np.inf to prohibit pairs, but raises ValueError: cost matrix is infeasible if those prohibitions leave no complete assignment.

Lab 2: DETR’s Hungarian matching

DETR (Carion et al., 2020) predicts a fixed set of NN (class, box) pairs and trains with a loss first matching predictions to objects. The cost of matching prediction ii to object jj of class cjc_j and box bj\vb{b}_j is

Cij=−p^i(cj)+λL1 ∥b^i−bj∥1−λgiouGIoU⁡(b^i,bj),\mathcal{C}_{ij} = -\hat p_i(c_j) + \lambda_{L1}\,\norm{\hat{\vb{b}}_i - \vb{b}_j}_1 - \lambda_{\text{giou}}\operatorname{GIoU}(\hat{\vb{b}}_i, \vb{b}_j),

with λL1=5\lambda_{L1} = 5 and λgiou=2\lambda_{\text{giou}} = 2 in the official implementation and boxes in normalized (center, width, height) format. The matrix is N×MN \times M and solved with linear_sum_assignment; predictions receiving no object train to predict the “nothing” class. Because assignment is one-to-one, the model learns not to duplicate detections and nonmaximum suppression disappears.

[ ]DETR cost matrix and assignmentBrowser
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

def a_xyxy(z):
    return np.stack([z[:, 0] - z[:, 2] / 2, z[:, 1] - z[:, 3] / 2, z[:, 0] + z[:, 2] / 2, z[:, 1] + z[:, 3] / 2], 1)

def giou(a, b):
    """IoU generalizado entre cajas (x0, y0, x1, y1): a (N, 4), b (M, 4) -> (N, M)."""
    a, b = a[:, None, :], b[None, :, :]
    area = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
    iw = np.clip(np.minimum(a[..., 2], b[..., 2]) - np.maximum(a[..., 0], b[..., 0]), 0, None)
    ih = np.clip(np.minimum(a[..., 3], b[..., 3]) - np.maximum(a[..., 1], b[..., 1]), 0, None)
    inter = iw * ih
    union = area(a) + area(b) - inter
    envolvente = (np.maximum(a[..., 2], b[..., 2]) - np.minimum(a[..., 0], b[..., 0])) * \
                 (np.maximum(a[..., 3], b[..., 3]) - np.minimum(a[..., 1], b[..., 1]))
    return inter / union - (envolvente - union) / envolvente

def coste_detr(prob, cajas, clases_gt, cajas_gt, w_cls=1.0, w_l1=5.0, w_giou=2.0):
    c_cls = -prob[:, clases_gt]
    c_l1 = np.abs(cajas[:, None, :] - cajas_gt[None, :, :]).sum(-1)
    c_giou = -giou(a_xyxy(cajas), a_xyxy(cajas_gt))
    return w_cls * c_cls + w_l1 * c_l1 + w_giou * c_giou

rng = np.random.default_rng(0)
M, N, K = 6, 20, 4                                  # objetos, predicciones, clases
cajas_gt = np.column_stack([rng.uniform(0.2, 0.8, (M, 2)), rng.uniform(0.08, 0.25, (M, 2))])
clases_gt = rng.integers(0, K, M)
cajas = np.column_stack([rng.uniform(0.1, 0.9, (N, 2)), rng.uniform(0.05, 0.3, (N, 2))])
cajas[:M] = cajas_gt[rng.permutation(M)] + rng.normal(0, 0.03, (M, 4))   # seis predicciones buenas
logits = rng.normal(0, 1, (N, K + 1))
prob = np.exp(logits) / np.exp(logits).sum(1, keepdims=True)

Cm = coste_detr(prob, cajas, clases_gt, cajas_gt)
filas, cols = linear_sum_assignment(Cm)
base = filas[np.argsort(cols)]
print("forma de la matriz de costes:", Cm.shape)
print("predicción asignada a cada objeto:", base)
mejor_obj = Cm.argmin(1)
print("si cada predicción eligiera su objeto más barato, cuántas se disputarían cada objeto:", np.bincount(mejor_obj, minlength=M))

def fraccion_cambios(sigma, reps=200):
    fr = []
    for _ in range(reps):
        cp = cajas + rng.normal(0, sigma, cajas.shape)
        cp[:, 2:] = np.clip(cp[:, 2:], 0.01, None)
        pr = np.clip(prob + rng.normal(0, sigma, prob.shape), 1e-6, None)
        pr /= pr.sum(1, keepdims=True)
        f, c = linear_sum_assignment(coste_detr(pr, cp, clases_gt, cajas_gt))
        fr.append(np.mean(f[np.argsort(c)] != base))
    return np.mean(fr)

sigmas = [0.0025, 0.005, 0.01, 0.02, 0.035, 0.05, 0.075, 0.1, 0.15]
cambios = [fraccion_cambios(s) for s in sigmas]
for s, c in zip(sigmas, cambios):
    print(f"sigma = {s:<6}  fracción de objetos que cambian de predicción: {c:.3f}")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.2))
for k, (x0, y0, x1, y1) in enumerate(a_xyxy(cajas)):
    ax1.add_patch(mpatches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, lw=1, ls="--", ec="gray", alpha=0.6))
for j, (x0, y0, x1, y1) in enumerate(a_xyxy(cajas_gt)):
    ax1.add_patch(mpatches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, lw=2, ec=f"C{j}"))
    i = base[j]
    ax1.plot([cajas_gt[j, 0], cajas[i, 0]], [cajas_gt[j, 1], cajas[i, 1]], "-", color=f"C{j}", lw=1.5)
    ax1.plot(cajas[i, 0], cajas[i, 1], "o", color=f"C{j}")
ax1.set_xlim(0, 1); ax1.set_ylim(1, 0); ax1.set_aspect("equal")
ax1.set_title("objetos (color), predicciones (gris) y asignación")
ax2.plot(sigmas, cambios, "o-")
ax2.set_xlabel("ruido σ en cajas y probabilidades"); ax2.set_ylabel("fracción de objetos reasignados")
ax2.set_title("la asignación no es continua")
plt.tight_layout(); plt.show()

Each object gets exactly one prediction, whereas when each prediction picks its cheapest object, several compete for the same one. The second plot shows the price: assignment is a piecewise constant function of predictions, and small noise changes it abruptly. With σ=0.05\sigma = 0.05, just over one fifth of objects change prediction, and with σ=0.1\sigma = 0.1, more than half. During training this means one query receives different targets across steps, one reason DETR converges slowly; DN-DETR (Li et al., 2022) identifies this explicitly and alleviates it by adding noisy queries whose targets are known without matching.

Common mistakes

Exercises

QuizWhat greedy guarantees
A greedy algorithm adds edges to MM while possible and ends with ∣M∣=40|M| = 40. What can be guaranteed about maximum matching size ν\nu?
NumericHow much remains, from path length
Hopcroft–Karp has a matching with ∣M∣=300|M| = 300 and its shortest augmenting path now has 21 edges. Using that M△M∗M \triangle M^* contains ν−∣M∣\nu - |M| disjoint augmenting paths, what is the best upper bound for ν\nu obtained by counting MM edges used by each path?
NumericA 4×4 assignment
Calculate the minimum assignment cost (one different column per row) for C=[1346367452796989]\mat{C} = \begin{bmatrix} 1 & 3 & 4 & 6 \\ 3 & 6 & 7 & 4 \\ 5 & 2 & 7 & 9 \\ 6 & 9 & 8 & 9 \end{bmatrix}.
QuizWhich potentials certify the optimum?
For the previous matrix and the assignment costing 15, which pairs (u,v)(u, v) prove it optimal?

More than one answer may be correct.

NumericTransportation with two warehouses
Two warehouses, A with 5 units and B with 4, supply three stores demanding 3 units each. Unit costs from A to stores are (4,5,8)(4, 5, 8) and from B, (5,3,12)(5, 3, 12). What is minimum transportation cost?
QuizDijkstra after the first augmentation
You implement successive shortest paths with initially nonnegative costs and use Dijkstra on original residual costs ww in every iteration. What can happen?
QuizPadding a rectangular matrix
You have 3 workers and 5 tasks; each worker does exactly one, and each undone task incurs penalty pjp_j. You want to use a Hungarian implementation accepting only square matrices. How do you pad?
QuizWhich tool?
Which problem–tool pairs are correct?

More than one answer may be correct.

NumericDeferred acceptance worst case
With n=50n = 50 proposers and 50 receivers, what maximum proposal count can deferred acceptance make according to the theorem’s bound?
ProofBerge’s theorem
Prove: A matching MM is maximum iff no augmenting path exists relative to MM.
0
‘Maximum implies no augmenting path’ is immediate: if PP is augmenting, M△PM \triangle P has one more edge. Conversely, suppose MM is not maximum and let M∗M^* be a matching with ∣M∗∣>∣M∣|M^*| > |M|.

Step 1 of 4. What object do you study?

ProofDeferred acceptance stability and optimality
Prove: Deferred acceptance terminates with a perfect stable matching, and each proposer obtains their best valid partner (their best partner in any stable matching).
0
Call the result MM. Proposers move down lists; receivers accept provisionally and only improve.

Step 1 of 4. Why does it terminate?

Code50×50 assignment with certificate
Implement asignacion(C) for a square matrix C (list of lists or NumPy array) returning (asig, u, v): asig[i] is row i’s column in a minimum-cost assignment, and u, v are potentials with u[i] + v[j] <= C[i][j] in every cell and sum(u) + sum(v) equal to the cost of asig. Use the Hungarian algorithm with potentials (do not call linear_sum_assignment); in O(n3)O(n^3), a 50×50 matrix is solved in milliseconds.
import numpy as np

def asignacion(C):
  C = np.asarray(C, dtype=float)
  n = C.shape[0]
  # tu código: inserta las filas una a una, haz crecer el árbol alternante
  # con la holgura mínima de cada columna y ajusta los potenciales
  asig = list(range(n))
  u = [0.0] * n
  v = [0.0] * n
  return asig, u, v
Shift+Enter to run

Summary

Key idea
Matching well means finding both a solution and a certificate: augmenting paths and a vertex cover for cardinality, an assignment and potentials for cost, a flow and distances without negative cycles for minimum-cost flow; stability, by contrast, is certified pair by pair.
  • A matching is maximum iff it has no augmenting paths (Berge). In bipartite graphs searching for them is Ford–Fulkerson on a unit network, O(VE)\bigO(VE), and minimum cut gives König’s cover.
  • Hopcroft–Karp flips a maximal set of shortest vertex-disjoint augmenting paths per phase; minimum length rises by at least 2 each phase, there are O(V)\bigO(\sqrt{V}) phases and cost is O(EV)\bigO(E\sqrt{V}). It is Dinic on the unit network.
  • Assignment is a linear program with integer optimum (Birkhoff–von Neumann). Hungarian maintains feasible potentials and a matching of tight cells, raises potentials just enough to create new cells, and ends when primal and dual agree, in O(n3)\bigO(n^3).
  • Minimum-cost flow is optimal iff the residual has no negative cycles, i.e. potentials exist with nonnegative reduced costs. Successive shortest paths use those potentials to apply Dijkstra every iteration.
  • In general graphs, odd cycles break the flow reduction; Edmonds’ blossom algorithm contracts them and remains polynomial.
  • Deferred acceptance always yields a stable matching, best for proposers and worst for receivers; truth-telling is dominant for proposers but not receivers.