Bipartite Graphs and Matching
A graph is bipartite if its vertices split into two sides and so that every edge goes between the sides. Applicants and jobs, students and project slots, ads and ad slots, doctors and hospitals: assignment problems are bipartite graphs, and a solution is a matching. This lesson proves Hall's theorem, which says exactly when everyone can be matched, and shows the stable matching algorithm used for residency placements.
Bipartite graphs
Theorem. A graph is bipartite if and only if it has no cycle of odd length.
One direction is easy: a cycle alternates sides, so it returns to its start side only after an even number of steps. For the other, color a vertex , its neighbours , their neighbours , and so on (BFS); an odd cycle is the only way to reach a vertex from both sides. The BFS gives an algorithm that either 2-colors the graph or finds a conflict.
from collections import deque
def two_color(n, edges):
adj = {v: [] for v in range(n)}
for u, v in edges:
adj[u].append(v); adj[v].append(u)
side = {}
for s in range(n):
if s in side:
continue
side[s] = 0
q = deque([s])
while q:
u = q.popleft()
for w in adj[u]:
if w not in side:
side[w] = 1 - side[u]; q.append(w)
elif side[w] == side[u]:
return None, (u, w)
return side, None
print(two_color(6, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)])) # even cycle
print(two_color(5, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])) # odd cycle({0: 0, 1: 1, 5: 1, 2: 0, 4: 0, 3: 1}, None)
(None, (2, 3))
Matchings and Hall's theorem
A matching is a set of edges with no shared vertex. A matching covers if every vertex of is matched. For a set , let be the set of neighbours of in .
Hall's Theorem. There is a matching covering if and only if every subset satisfies .
The condition is clearly necessary: if 3 applicants are together qualified for only 2 jobs, they cannot all be placed. The surprise is that it is also sufficient (proof by strong induction on , splitting on whether some proper subset is "tight" with ).
Corollary. If every vertex of has degree at least and every vertex of has degree at most , there is a matching covering . In particular, every regular bipartite graph has a perfect matching.
Finding a maximum matching
The augmenting path algorithm grows a matching: from an unmatched left vertex, search for a path that alternates unmatched/matched edges and ends at an unmatched right vertex; flipping the edges on that path adds one to the matching. When no augmenting path exists, the matching is maximum.
def max_matching(adj):
"""adj: dict left -> list of right vertices. Returns dict right -> left."""
match = {}
def try_assign(u, seen):
for v in adj[u]:
if v in seen:
continue
seen.add(v)
if v not in match or try_assign(match[v], seen):
match[v] = u
return True
return False
for u in adj:
try_assign(u, set())
return match
skills = {
"ana": ["backend", "data"],
"ben": ["backend"],
"chi": ["frontend", "backend"],
"dev": ["data", "ops"],
"eve": ["frontend"],
}
m = max_matching(skills)
print("matched:", sorted((u, v) for v, u in m.items()))
print("size:", len(m), "of", len(skills))matched: [('ana', 'data'), ('ben', 'backend'), ('chi', 'frontend'), ('dev', 'ops')]
size: 4 of 5
Only 4 of 5 people can be placed. Hall's condition explains why: has , two jobs for three people.
Stable matching
When both sides have preferences, a matching of applicants to employers is stable if no applicant and employer prefer each other over their current partners (such a pair is a rogue couple). The Gale–Shapley algorithm always finds a stable matching: each unmatched applicant proposes to the best employer not yet tried; each employer keeps the best proposal so far and rejects the rest. It runs in proposals, and the result is the best stable matching possible for every applicant (the proposing side). The U.S. National Resident Matching Program uses a variant.
In software
Matching algorithms assign tasks to workers, rides to drivers and ads to slots; with weights, the Hungarian algorithm finds a maximum-weight matching. Bipartite checks detect conflicts, such as whether a set of meetings can be split into two rooms when certain pairs cannot share a room.
Exercises
Exercise 1: Bipartite?
Which are bipartite: (a) ; (b) ; (c) a tree; (d) ?
Answer
(a) yes; (b) no; (c) yes; (d) no.
Solution
A graph is bipartite exactly when it has no odd cycle. is an even cycle; and (a triangle) are odd cycles; a tree has no cycles at all.
Exercise 2: Check Hall's condition
Left , right , edges . Is there a matching covering the left side?
Answer
No.
Solution
has , so . Vertices 2 and 3 both need .
Exercise 3: Regular graphs
Every student in a class has exactly 3 favourite songs among 30, and every song is the favourite of exactly 3 students; there are 30 students. Can each student present a different favourite song?
Answer
Yes.
Solution
The student-song graph is 3-regular and bipartite. For a set of students there are edges leaving , and they land on songs that each take at most 3 of them, so . Hall's theorem gives a perfect matching.
Exercise 4: Gale–Shapley (code)
Run proposals for applicants A, B, C with preferences A: x > y > z, B: y > x > z, C: x > y > z and employers x: B > A > C, y: A > B > C, z: A > B > C.
Answer
A–x, B–y, C–z.
Solution
apps = {"A": ["x", "y", "z"], "B": ["y", "x", "z"], "C": ["x", "y", "z"]}
emps = {"x": ["B", "A", "C"], "y": ["A", "B", "C"], "z": ["A", "B", "C"]}
rank = {e: {a: i for i, a in enumerate(p)} for e, p in emps.items()}
free, nxt, holds = list(apps), {a: 0 for a in apps}, {}
while free:
a = free.pop(0)
e = apps[a][nxt[a]]; nxt[a] += 1
if e not in holds:
holds[e] = a
elif rank[e][a] < rank[e][holds[e]]:
free.append(holds[e]); holds[e] = a
else:
free.append(a)
print(sorted((a, e) for e, a in holds.items()))[('A', 'x'), ('B', 'y'), ('C', 'z')]
A proposes to x, B to y, C to x (rejected, x prefers A), C to y (rejected), C to z. No rogue pair: C would like x or y, but both prefer their current partner to C.
Test yourself
A graph is bipartite if and only if…
- it is connected
- it has no odd cycle
- it has an even number of vertices
- every vertex has even degree
Hall's condition for a matching covering is…
- for every
- every vertex has degree 1
- the graph is a tree
What does an augmenting path do to a matching?
- Removes an edge
- Increases its size by one when its edges are flipped
- Checks Hall's condition
- Makes it stable