 # Stable Marriage Problem

Stable Marriage Problem is the problem of finding a stable matching between two sets of elements given a set of preferences for each element. Formally, given a set M = {m1, m2, …, mn} of n men, a set W = {w1, w2, …, wn} of n women, a preference list (i.e., an ordering of n men) for each woman and a preference list (i.e., an ordering of n women) for each man, the problem is to find a set S of pairs (m,w) for some m ∈ M and w ∈ W such that

• Each m ∈ M and w ∈ W appears in exactly one pair in S
• If (m, w) ∈ S and (m’, w’) ∈ S, then it cannot be the case that m prefers w’ to w and w’ prefers m to m’

This problem comes up in several real-world scenarios from a self-enforcing college recruitment procedure to assignment of patients to hospitals. Mathematicians David Gale and Lloyd Shapley proved that, for any equal number of men and women, it is always possible to solve the problem and make all marriages stable. The Gale-Shapley algorithm, as described in Algorithm Design by Kleinberg and Tardos, is as follows:

It is easy to see that the algorithm terminates after at most n2 iterations and in fact, has a running time of  O(n2).

Take a look at C++ implementation.

Try your hand at problem STABLEMP which uses this idea.

Reference: Algorithm Design by Kleinberg and Tardos