Online Bipartite Matching and Greedy
The last section of the course turns from minimizing cost to maximizing value. Its basic problem was introduced by Karp, Vazirani and Vazirani (1990): online bipartite matching. One side of a bipartite graph is known in advance (ad slots, servers, items); the vertices of the other side arrive one at a time (search queries, jobs, customers), each revealing its edges on arrival, and each must be matched immediately and irrevocably to a free neighbour or left unmatched. The question is how large a matching an online algorithm can guarantee compared with a maximum matching of the whole graph. This lesson analyses the greedy algorithm, proves that no deterministic algorithm beats , and shows that the obvious randomization does not help either, setting the stage for RANKING.
The model
The graph is . The offline vertices are known from the start. The online vertices arrive in an order chosen by the adversary; when arrives, its edges to are revealed, and the algorithm either matches to a currently unmatched neighbour or leaves it unmatched forever. The value is the size of the final matching, compared with , the size of a maximum matching of . An algorithm is -competitive () if it always obtains at least (in expectation, for randomized algorithms against an oblivious adversary).
Greedy is -competitive
Greedy: match each arriving vertex to any free neighbour if one exists. Every greedy algorithm produces a maximal matching: when it finishes, no edge has both endpoints free (the online endpoint of such an edge would have been matched on arrival).
Theorem. Every greedy algorithm, whatever its tie-breaking rule, obtains at least .
Proof
Let be the greedy matching and a maximum matching. For every edge , at least one of and is matched in , because is maximal. Each edge of has two endpoints, so it can account for at most two edges of this way. Hence .
The program runs greedy with two tie-breaking rules on the upper-triangular graph: offline vertices and online vertices , where is adjacent to . It has a perfect matching ( to ), but greedy that prefers the last free neighbour matches to and runs out after arrivals. The maximum matching is computed by augmenting paths, the algorithm practised in Maximum Bipartite Matching.
def max_matching(adj, n_offline):
match_u = [None] * n_offline
def augment(v, seen):
for u in adj[v]:
if u not in seen:
seen.add(u)
if match_u[u] is None or augment(match_u[u], seen):
match_u[u] = v
return True
return False
return sum(augment(v, set()) for v in range(len(adj)))
def greedy(adj, n_offline, prefer):
free = [True] * n_offline
size = 0
for v, nbrs in enumerate(adj): # online vertices arrive in index order
cands = [u for u in nbrs if free[u]]
if cands:
u = min(cands) if prefer == "first" else max(cands)
free[u] = False
size += 1
return size
for n in [4, 10, 50]:
adj = [list(range(j, n)) for j in range(n)] # v_j likes u_j .. u_{n-1}
opt = max_matching(adj, n)
print(f"n = {n:2}: OPT {opt}, greedy-first {greedy(adj, n, 'first')}, greedy-last {greedy(adj, n, 'last')}")n = 4: OPT 4, greedy-first 4, greedy-last 2
n = 10: OPT 10, greedy-first 10, greedy-last 5
n = 50: OPT 50, greedy-first 50, greedy-last 25
With the lucky rule greedy is optimal here; with the unlucky one it gets exactly half. Of course the adversary picks the instance after seeing the rule, so for the "first" rule it would simply relabel the vertices.
In C++
Greedy against the maximum matching (Kuhn's augmenting-path algorithm) on seeded random bipartite graphs of growing density. On random graphs greedy is much better than , as usual for worst-case bounds.
#include <cstdio>
#include <random>
#include <vector>
struct Kuhn {
const std::vector<std::vector<int>>& adj;
std::vector<int> match_u;
std::vector<char> seen;
Kuhn(const std::vector<std::vector<int>>& a, int nu) : adj(a), match_u(nu, -1), seen(nu) {}
bool augment(int v) {
for (int u : adj[v]) {
if (seen[u]) continue;
seen[u] = 1;
if (match_u[u] < 0 || augment(match_u[u])) { match_u[u] = v; return true; }
}
return false;
}
int run() {
int size = 0;
for (int v = 0; v < (int)adj.size(); ++v) { std::fill(seen.begin(), seen.end(), 0); size += augment(v); }
return size;
}
};
int main() {
std::mt19937 rng(19);
const int n = 300;
for (int deg : {1, 2, 3, 5, 10}) {
std::vector<std::vector<int>> adj(n);
for (int v = 0; v < n; ++v)
for (int j = 0; j < deg; ++j) adj[v].push_back(rng() % n);
std::vector<char> taken(n, 0);
int greedy = 0;
for (int v = 0; v < n; ++v)
for (int u : adj[v])
if (!taken[u]) { taken[u] = 1; ++greedy; break; }
int opt = Kuhn(adj, n).run();
std::printf("degree %2d: OPT %3d, greedy %3d, ratio %.3f\n", deg, opt, greedy, double(greedy) / opt);
}
}degree 1: OPT 182, greedy 182, ratio 1.000
degree 2: OPT 252, greedy 230, ratio 0.913
degree 3: OPT 283, greedy 241, ratio 0.852
degree 5: OPT 296, greedy 263, ratio 0.889
degree 10: OPT 300, greedy 281, ratio 0.937
No deterministic algorithm beats
Theorem. For every deterministic online algorithm and every even , there is an instance with a perfect matching of size on which the algorithm matches at most vertices.
Proof
Work in pairs. For each pair of fresh offline vertices , an online vertex arrives adjacent to both. If the algorithm leaves unmatched, the next vertex of the pair is adjacent to only, and OPT matches both while the algorithm matches at most one. Otherwise it matches to one of them, say ; the next online vertex is adjacent only to , so it cannot be matched. OPT matches to and to . Each pair contributes 2 to OPT and at most 1 to the algorithm.
The adversary must see the algorithm's choice before revealing 's edges, which a deterministic algorithm cannot hide. The program builds this instance adaptively against three deterministic rules.
def adversarial_instance(rule, pairs):
"""Build the instance pair by pair, reacting to the algorithm's choices."""
taken, adj, matched = set(), [], 0
for p in range(pairs):
a, b = 2 * p, 2 * p + 1
nbrs = [a, b]
adj.append(nbrs)
choice = rule([u for u in nbrs if u not in taken], len(adj) - 1)
if choice is not None:
taken.add(choice)
matched += 1
trap = choice if choice is not None else a # the vertex the algorithm took
adj.append([trap])
if trap not in taken:
taken.add(trap)
matched += 1
return adj, matched
rules = {
"first free": lambda c, t: min(c) if c else None,
"last free": lambda c, t: max(c) if c else None,
"alternate": lambda c, t: (c[t % len(c)] if c else None),
}
for name, rule in rules.items():
adj, alg = adversarial_instance(rule, 20)
print(f"{name:10}: algorithm matched {alg} of {len(adj)} online vertices; a perfect matching has {len(adj)}")first free: algorithm matched 20 of 40 online vertices; a perfect matching has 40
last free : algorithm matched 20 of 40 online vertices; a perfect matching has 40
alternate : algorithm matched 20 of 40 online vertices; a perfect matching has 40
Does randomization help?
Against an oblivious adversary the instance must be fixed in advance, so the trap above no longer works: the adversary does not know which of and was taken. The natural randomized algorithm, RANDOM, matches each arriving vertex to a uniformly random free neighbour. Surprisingly, it is still only -competitive: Karp, Vazirani and Vazirani (1990) built instances on which RANDOM's expected matching is out of . The problem is that independent random choices at each arrival do not coordinate: early vertices with many neighbours spread over all offline vertices, including the ones that later vertices need.
The fix, also from Karp, Vazirani and Vazirani, is to make the randomness consistent: choose one random ranking of the offline vertices at the start and always match to the best-ranked free neighbour. That algorithm, RANKING, is -competitive, and no randomized algorithm does better (RANKING and Its Primal-Dual Proof). Two other variants change the model rather than the algorithm: if the online vertices arrive in a uniformly random order (but the graph is adversarial), plain greedy is already -competitive (Goel and Mehta, 2008); and with known i.i.d. arrivals, ratios above are possible.
Test yourself
Why is every greedy algorithm for online bipartite matching -competitive?
- It finds a maximum matching
- Its matching is maximal, so every edge of a maximum matching has an endpoint matched by greedy, and each greedy edge covers at most two such edges
- It is randomized
- It sees the whole graph
In the deterministic lower bound, what does the second online vertex of a pair look like?
- Adjacent to both offline vertices
- Adjacent only to the offline vertex the algorithm just used
- Adjacent to no vertex
- Adjacent to the unused offline vertex
What is the competitive ratio of RANDOM (a fresh uniformly random free neighbour at each arrival)?