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 predictions per image, each with a box and class distribution, and the image has 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 .
- 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 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 of edges with no shared endpoints, is maximum size, and a path is augmenting relative to if it alternates edges outside and inside and connects two free vertices. Flipping an augmenting path , i.e. moving to , adds one edge. Berge’s theorem says this suffices:
The proof, reconstructed step by step in the exercises, examines symmetric difference 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 , augmenting-path search is exactly Ford–Fulkerson on a residual graph. Build a network with a source joined to each with capacity 1, each edge directed from to with capacity 1, and each joined to sink 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 shares an endpoint with some edge of maximal (otherwise it could be added), and each edge of has two endpoints, each on at most one edge of . Therefore .
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 times per phase and the phase costs .
The figure shows lengths increasing strictly: in the three-phase graph. This is the key to the bound and follows from two lemmas.
Proof
In every vertex has degree at most 2, one per matching, so components are paths and cycles whose edges alternate between and . In each component the number of edges minus edges is , or , and the sum over components is . Thus at least components have difference : paths starting and ending with edges. Their endpoints are free in , because if endpoint had an edge , it would not be in (where already uses the path’s last edge) and would be in , extending the component. They are augmenting paths and are disjoint as distinct components.
∎Proof
Let augment relative to and , with . By the previous lemma, contains disjoint augmenting paths relative to , each with at least edges, so . Conversely , whose edge count is . Combining,
If shares any edge with the , we have . If it shares no edge, it shares no vertex either: every vertex of a is covered in by an edge of that , and , alternating relative to and free only at endpoints, would use that edge when passing through. Then is disjoint from the and also augmenting relative to (which agrees with outside the ); maximality means its length cannot be . Since and every augmenting path has odd length (it starts and ends with unmatched edges), .
∎Proof
By the second lemma, after phases the shortest augmenting path has at least edges. After phases, let be maximum. The first lemma gives disjoint augmenting paths each with at least vertices, so and . Each later augmenting phase increases by at least one, leaving at most such phases. Total augmenting phases are at most , and each costs .
∎This is a worst-case bound. In the lab, random graphs with thousands of vertices have far fewer than 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 touching every edge. Since matching edges share no endpoints, each needs a different vertex of , and always. König’s theorem says equality holds in bipartite graphs, and the flow reduction proves this in three lines while constructing .
Give edges infinite capacity and retain capacity 1 on and (maximum flow is unchanged because each receives at most one unit). After maximum flow, let be vertices reachable from in the residual and . No edge crosses from to its complement because its capacity is infinite and it is never saturated. The cut edges are therefore with and with , and
is a cover: if edge has , then and ; otherwise . Its size is cut capacity, which equals maximum flow, . In matching terms, are vertices reachable by alternating paths from free vertices of : exactly Hopcroft–Karp’s final BFS, which finds no free vertex of . The red squares at the end of the previous figure are that .
The assignment problem
Now all pairs are possible and each has a cost. Given matrix , choose permutation minimizing . As a linear program, with the fraction of row assigned to column :
Dual variables (one per row) and (one per column) are potentials, and is reduced cost. Weak duality takes one line: for any feasible and , , because rows and columns of 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 be doubly stochastic and the row-column bipartite graph with edge for each . For a set of rows, total mass is and all lies in neighboring columns , each receiving at most 1; hence . By Hall’s theorem, has a perfect matching, i.e. permutation with for every . Let . If , is the permutation. Otherwise with doubly stochastic and at least one more zero entry; by induction on positive entries, 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 is optimal iff feasible potentials exist ( in every cell) with in every selected cell.
Then : primal and dual agree. Cells with 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 (, ), add to and subtract it from , and is unchanged, so tree and edges remain tight; in it drops and does not go negative because is the minimum there; in it rises ; elsewhere it is unchanged. Feasibility is preserved, at least one new tight cell leaves the tree, and dual value rises because the tree always has one more row than columns.
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 , a lower bound; the optimum is with assignment , and the algorithm ends with potentials , summing exactly to . Those ten numbers are the certificate: anyone can check in a minute that 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, cost equals dual value. Since free columns retain and others only decrease, any other assignment of those rows costs at least , which is cost. Thus after rows, is an optimal assignment of the first rows.
Cost. Each row adds at most columns to the tree. If each column’s minimum slack relative to the tree is stored, , each step updates those slacks with the newly entered row and finds their minimum in . This is per row and total. Without the slack array, recomputing from scratch costs , 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 to ), maximum flow (zero costs and return edge with cost ), 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 is the maximum-flow residual with costs: edge with slack costs , and its reverse, when carrying flow, costs (undoing one unit returns its cost).
Proof
If a negative cycle exists in , sending one unit (or the minimum slack) around it gives a cheaper feasible flow. Conversely, if is feasible and cheaper, (interpreted in : increases on forward edges, decreases on reverse edges) is a circulation in of cost . 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 from an auxiliary vertex connected to all at cost 0 are well-defined and satisfy , which is ; and if , 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 is minimum-cost-flow complementary slackness. For assignment, of a row is and of a column is , and equals .
Successive shortest paths
The most direct algorithm sends flow from to always along the cheapest residual path:
- Initial potentials: if all costs are nonnegative; with negative costs (but no negative cycles), are Bellman–Ford distances from an auxiliary vertex connected to all at cost 0, as in Johnson. In both cases, on every edge.
- While more flow is needed, compute distances from in with costs using Dijkstra; stop if is unreachable. Otherwise update at every vertex (unreachable vertices with increase by ) and push the greatest admissible amount along the shortest path (its bottleneck).
Proof
Assume in ; let be distances from at those costs ( for unreachable vertices), and . For each residual edge , triangle inequality and give
that is, . Vertices on the shortest path to have , so on them and their edges have exactly zero reduced cost. Pushing flow along that path introduces reverse edges whose reduced cost is ; some edges saturate and disappear, and no others appear. Thus 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 for flow of value : 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 units” is convex and piecewise linear in .
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, on every edge satisfies “each vertex covered at most once” with value , while . 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 admits an augmenting path in iff admits one in . With it, the algorithm finds each augmenting path in polynomial time. The original version is , careful implementations reach , and the Micali–Vazirani algorithm achieves , 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 for every odd-sized , 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 , and with maxcardinality=True gives a maximum-cardinality matching and, among those, maximum weight.
Stable matching
We switch worlds. There are residents and 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: and 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.
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 are matched to 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 proposals. Total .
Stability. Suppose blocks result : prefers to and prefers to . Because proposes in order, they proposed to before , and rejected them then or later dropped them for someone better. A hospital’s partner only improves, so prefers to . Contradiction.
Optimality. Suppose in some execution a resident is rejected by a valid partner, and consider the first such moment: rejects (or drops them) for , and stable matching has . Let . Until this moment no resident has been rejected by a valid partner, and proposed to after rejection by every hospital ranked above ; none was valid for , so is not ahead of on their list: prefers to (they differ because ). And prefers to . Then blocks , 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 hospital has and in another stable matching has someone worse, . In resident is not with (who has ), and is their best valid partner, so prefers to . Since prefers to , pair blocks , which was stable. Thus each receiver gets their worst valid partner in . 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.
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 : 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 : 23 versus 135 with . 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 connects to in that order and each search first tries every occupied column.
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 discards occupied with one check each and takes , so BFS and DFS each examine edges), while the simple algorithm examines order edges, : about 574 000 versus 22 650. A greedy initial matching would fix this case, which is why real implementations use it; bound guarantees the other cases.
König’s certificate comes from the final BFS: vertices reachable by alternating paths from free vertices on the left.
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 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.
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, and , 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):
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, , 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:
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.
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
| Problem | Function | Algorithm |
|---|---|---|
| Maximum bipartite matching | networkx.bipartite.hopcroft_karp_matching(G, top_nodes) | Hopcroft–Karp |
| Same on sparse matrix | scipy.sparse.csgraph.maximum_bipartite_matching(A) | Hopcroft–Karp in C |
| Assignment (rectangular, or ) | scipy.optimize.linear_sum_assignment(C, maximize=False) | modified Jonker–Volgenant, |
| Sparse assignment | scipy.sparse.csgraph.min_weight_full_bipartite_matching(A) | LAPJVsp |
| General-graph matching | networkx.max_weight_matching(G, maxcardinality) | Edmonds’ blossoms, |
| Minimum-cost flow, transportation | networkx.min_cost_flow(G), networkx.network_simplex(G) | network simplex |
| Large problems | OR-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 (class, box) pairs and trains with a loss first matching predictions to objects. The cost of matching prediction to object of class and box is
with and in the official implementation and boxes in normalized (center, width, height) format. The matrix is 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.
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 , just over one fifth of objects change prediction, and with , 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
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What object do you study?
Step 1 of 4. Why does it terminate?
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 , 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, vSummary
- A matching is maximum iff it has no augmenting paths (Berge). In bipartite graphs searching for them is Ford–Fulkerson on a unit network, , 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 phases and cost is . 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 .
- 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.