Zuerst das Quiz zu Kapitel 4Zuerst Kapitel 4 prüfen
Mach das Quiz zu Kapitel 4: 10 Fragen, bestanden mit 7 richtigen. Du kannst es beliebig oft wiederholen.
Pairs That Work
Kapitel 5, Lektion 3 von 3
Matching: the biggest pairing, proofs of the impossible, the cheapest assignment and stable pairs.
Auf Englisch gesprochen. Oben kannst du englische, arabische, deutsche, spanische oder französische Untertitel einschalten.
Schriftliche Lektion
12 Min. LesezeitAuf Englisch verfasst.
Every March, tens of thousands of new doctors in the United States find out, on the same day, which hospital they will train at. Nobody haggles. Each doctor ranks the hospitals, each hospital ranks the doctors, and an algorithm makes every match at once.
Doctors and hospitals, workers and jobs, patients and kidney donors: each time, two kinds of things must be paired, one to one. After two lessons of problems nobody can solve quickly, here is good news: pairing has fast, exact algorithms. This lesson covers the chain trick that finds the biggest matching, a short proof when a perfect one is impossible, the Hungarian method for the cheapest pairing, and the stable matching that won a Nobel prize.
One partner each
Matchings live in bipartite graphs, the two-sided graphs from lesson 16. Here there are five technicians on the left, five jobs on the right, and an edge when a technician can do that job:
| Technician | Ana | Ben | Cai | Dev | Eva |
|---|---|---|---|---|---|
| Can do jobs | 1, 2 | 2, 3 | 3, 4 | 4, 5 | 1 |
- A matching is a set of edges where no two share a vertex: nobody works two jobs, and no job gets two technicians.
- A matching that covers every vertex is perfect: every technician busy, every job done.
The obvious method is greedy: go down the list, and give each technician the first free job they can do. Ana takes job 1, Ben job 2, Cai job 3 and Dev job 4. And Eva, who can only do job 1, is left with nothing.
Greedy stops at four pairs, and Eva is left out.
No edge can be added now, so this matching is maximal. But it is not maximum: the biggest matching here has five pairs. Maximal means "cannot be extended"; maximum means "as large as possible".
The chain trick
The fix is a chain. Start at Eva, who is free, and follow the edge to job 1. Job 1 belongs to Ana, so follow the matched edge back to Ana. Ana can also do job 2, which Ben holds. Ben can also do 3, Cai can also do 4, and Dev can also do job 5, which is free:
This is an augmenting path: it starts and ends at free vertices, and its edges alternate, outside the matching, inside, outside, inside.
Now flip every edge on the path: the outside edges come in, and the inside edges go out. Everyone shifts one job along, and Eva gets job 1. The path had one more outside edge than inside edge, so the matching grows by exactly one: five pairs, a perfect matching.
Flip the augmenting path: five pairs.
Berge's theorem (Claude Berge, 1957) says this is all you ever need:
Why. Lay a bigger matching over a smaller one, and keep only the edges that belong to exactly one of them. Every vertex touches at most one edge of each, so these edges break into alternating paths and cycles. Cycles and even paths use equally many edges of both matchings, so, since the bigger matching has more edges, at least one path has more edges from the bigger matching. That path starts and ends at vertices the smaller matching leaves free: it is augmenting.
So the algorithm is simple: search for an augmenting path, flip it, and repeat. Each search is a breadth-first (or depth-first) search, and there are at most as many rounds as pairs. The Hopcroft-Karp algorithm speeds this up by flipping many shortest paths per round.
Proving it cannot be done
Now suppose Ben loses the certificate for job 3 and can only do job 2. Search as long as you like: you will never place all five. And there is a short proof, found by Philip Hall in 1935.
Look at Ana, Ben and Eva. Between them they can only do jobs 1 and 2. Three people, two jobs: one of them must go without.
Ana, Ben and Eva can only do jobs 1 and 2.
The "only if" part is the counting we just did. The surprise is the "if": when no group is short of jobs, a matching of everyone always exists (an augmenting path can always be found).
Four years earlier, Dénes Kőnig, whose textbook we met in lesson 1, proved a close cousin:
Here jobs 1 and 2, plus Cai and Dev, touch every edge. That is four vertices, so no matching can have more than four pairs, because every pair needs its own vertex from the cover. And Eva with job 1, Ben with 2, Cai with 3 and Dev with 4 is a matching of four, so both numbers are exactly 4.
A vertex cover of four proves no matching has five pairs.
A maximum matching and a minimum cover of the same size certify each other: neither can be improved.
The Hungarian method
Real jobs have costs. Say each technician needs a different number of minutes to reach each job, and we want the perfect matching with the smallest total time. This is the assignment problem.
| Minutes | Job 1 | Job 2 | Job 3 | Job 4 |
|---|---|---|---|---|
| Ana | 70 | 35 | 50 | 55 |
| Ben | 35 | 35 | 15 | 25 |
| Cai | 60 | 70 | 20 | 65 |
| Dev | 40 | 15 | 25 | 45 |
Four technicians and four jobs allow 4! = 24 plans; twenty would allow 20!, more than two billion billion.
Greedy again. Each technician in turn takes the closest free job: Ana job 2 (35), Ben job 3 (15), Cai job 1 (60), Dev job 4 (45). Ben grabbed job 3, the only close job Cai had, and the plan costs 155 minutes.
Greedy: 155 minutes.
In 1955 Harold Kuhn published a better way and called it the Hungarian method, after the work of Kőnig and Jenő Egerváry. The key idea:
- Rows. Take each row's smallest time away from that row: 35, 15, 20 and 15.
- Columns. Then each column's smallest from that column: 20, 0, 0 and 10. Now the zeros mark free choices, and we have taken away 35 + 15 + 20 + 15 + 20 + 10 = 115 minutes. No plan can cost less than that.
- Cover the zeros. Can we pick four zeros, one in each row and each column? Three lines cover every zero (rows Ben and Cai, column job 2), so no: by Kőnig's theorem we can only pick three.
- Shift. The smallest uncovered number is 5. Take 5 from every uncovered row (Ana, Dev) and add 5 to every covered column (job 2). The net effect lowers every plan by 5, a new zero appears, and the bound rises to 120.
| After the shift | Job 1 | Job 2 | Job 3 | Job 4 |
|---|---|---|---|---|
| Ana | 10 | 0 | 10 | 5 |
| Ben | 0 | 25 | 0 | 0 |
| Cai | 20 | 55 | 0 | 35 |
| Dev | 0 | 0 | 5 | 15 |
Now four zeros sit in different rows and columns: Ana to job 2, Ben to job 4, Cai to job 3 and Dev to job 1. That plan costs 35 + 25 + 20 + 40 = 120 minutes, exactly the bound we proved, so nothing can beat it. (The next best of the 24 plans costs 125.)
Four independent zeros: 120 minutes, the proven bound.
A twist of history: in 2006 scholars found that Carl Jacobi had solved the same problem in the 1800s. The solution was published in Latin in 1890, after his death, and then overlooked for more than a century. Kuhn's method, later made O(n³), is still how the problem is solved today.
Stable pairs
Back to the doctors. Their problem has a twist: both sides have wishes. A pairing is unstable if a doctor and a hospital both prefer each other to the partners they were given. They would simply break away: that pair is a blocking pair.
| Doctor | Ranks hospitals | Hospital | Ranks doctors |
|---|---|---|---|
| Mia | East, West, North | North | Omar, Mia, Noor |
| Noor | West, East, North | East | Mia, Omar, Noor |
| Omar | West, East, North | West | Mia, Omar, Noor |
The plan with the smallest total rank puts Mia at East, Noor at West and Omar at North (total rank 10). But Omar prefers West, and West prefers Omar to Noor. That pair would break the plan.
The lowest total rank is not stable: Omar and West break away.
In 1962 David Gale and Lloyd Shapley showed that a stable plan always exists, and gave a way to find it, deferred acceptance:
- Each free doctor proposes to the favourite hospital that has not turned them down yet.
- Each hospital holds its best offer so far and rejects the rest. Holding is not a promise.
- Repeat until nobody is free.
On our example: Mia proposes to East, and Noor to West. Then Omar proposes to West, and West drops Noor for Omar. Noor tries East, but East prefers Mia. Noor ends up at North.
Deferred acceptance: West drops Noor for Omar, and Noor ends at North.
Why the result is stable. Suppose doctor d prefers hospital h to their final partner. Then d proposed to h earlier, and h turned d down, either at once or later, only ever for someone it liked better. A hospital's held offer only improves, so h ends with someone it prefers to d. No blocking pair can exist.
Here it is the only stable plan (total rank 11), and Noor lands on the last choice on the list: stable does not mean everyone is happy. And the side that proposes does best: each proposer ends up with the best partner they could get in any stable plan.
Practice got there first. The American residency match began in 1952. In 1984 Alvin Roth showed that its procedure was essentially deferred acceptance with hospitals proposing: ten years before the theory. In 1998 the match switched to doctors proposing, with a design by Roth, and in 2012 Roth and Shapley shared the Nobel memorial prize in economics, for stable allocations and market design.
From the residency match to a Nobel prize.
Both algorithms are short in Python:
def max_matching(can):
job_of, tech_of = {}, {}
def augment(t, seen):
for j in can[t]:
if j in seen:
continue
seen.add(j)
# j is free, or its technician can move to another job
if j not in tech_of or augment(tech_of[j], seen):
job_of[t], tech_of[j] = j, t
return True
return False
for t in can:
augment(t, set())
return job_of
def deferred_acceptance(doc_prefs, hos_prefs):
rank = {h: {d: i for i, d in enumerate(p)} for h, p in hos_prefs.items()}
nxt = {d: 0 for d in doc_prefs}
held, free = {}, list(doc_prefs)
while free:
d = free.pop(0)
h = doc_prefs[d][nxt[d]]
nxt[d] += 1
if h not in held:
held[h] = d
elif rank[h][d] < rank[h][held[h]]:
free.append(held[h]) # the hospital drops its old offer
held[h] = d
else:
free.append(d)
return {d: h for h, d in held.items()}
can = {"Ana": [1, 2], "Ben": [2, 3], "Cai": [3, 4], "Dev": [4, 5], "Eva": [1]}
len(max_matching(can)) # 5
can["Ben"] = [2] # Ben loses job 3
len(max_matching(can)) # 4
doc = {"Mia": ["East", "West", "North"], "Noor": ["West", "East", "North"], "Omar": ["West", "East", "North"]}
hos = {"North": ["Omar", "Mia", "Noor"], "East": ["Mia", "Omar", "Noor"], "West": ["Mia", "Omar", "Noor"]}
deferred_acceptance(doc, hos) # {'Mia': 'East', 'Omar': 'West', 'Noor': 'North'}
In the world
- Kidney exchange. A patient may have a willing donor whose kidney is not a match. Swap donors between two such pairs, and both patients get a transplant. Exchanges now search whole countries for cycles and long chains of these swaps, with matching algorithms at the core.
- School choice. New York City assigns students to high schools with deferred acceptance.
- Ride services pair drivers with riders around the clock.
Wherever two sides must be paired, a matching algorithm is close by.
Key ideas
- A matching pairs vertices across a bipartite graph. Each augmenting path makes it one bigger, and when none is left it is maximum (Berge).
- Hall's theorem (a group with too few options) and Kőnig's theorem (a small vertex cover) give short proofs that nothing better exists.
- The Hungarian method finds the cheapest perfect matching by shifting rows and columns until the zeros line up; the amount taken away is a lower bound that the final plan meets.
- Deferred acceptance always finds a stable matching when both sides have preferences, and the proposing side gets its best stable partner.
Check yourself
1. In the first technician graph, is the matching Ana-job 2, Ben-job 3, Cai-job 4, Dev-job 5 maximal? Is it maximum?
2. Four technicians together can do only jobs 1, 2 and 3. What is the largest number of the four that can all be placed?
3. In the assignment table, Dev's time for job 1 rises from 40 to 50. Is Ana 2, Ben 4, Cai 3, Dev 1 still the best plan?
Practice on the platform
The work assignment guide solves a real crew of technicians with the Hungarian method and shows Hall's theorem on a sick day. In the bipartite check visualizer, import our five technicians and five jobs and run the check: it splits the graph into two sides, technicians on one and jobs on the other, exactly the shape a matching needs.
Als Nächstes