TExcelTAD
Home › Online Algorithms & Competitive Analysis › Online Bipartite Matching and Greedy

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 12\frac{1}{2}, and shows that the obvious randomization does not help either, setting the stage for RANKING.

The model

The graph is G=(U,V,E)G = (U, V, E). The offline vertices UU are known from the start. The online vertices v1,v2,…∈Vv_1, v_2, \ldots \in V arrive in an order chosen by the adversary; when vtv_t arrives, its edges to UU are revealed, and the algorithm either matches vtv_t to a currently unmatched neighbour or leaves it unmatched forever. The value is the size of the final matching, compared with OPT\mathrm{OPT}, the size of a maximum matching of GG. An algorithm is cc-competitive (c≤1c \le 1) if it always obtains at least c⋅OPTc \cdot \mathrm{OPT} (in expectation, for randomized algorithms against an oblivious adversary).

Greedy is 12\frac{1}{2}-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 12OPT\frac{1}{2}\mathrm{OPT}.

Proof

Let MM be the greedy matching and M∗M^* a maximum matching. For every edge (u,v)∈M∗(u, v) \in M^*, at least one of uu and vv is matched in MM, because MM is maximal. Each edge of MM has two endpoints, so it can account for at most two edges of M∗M^* this way. Hence ∣M∗∣≤2∣M∣\lvert M^* \rvert \le 2 \lvert M \rvert.

The program runs greedy with two tie-breaking rules on the upper-triangular graph: nn offline vertices u1,…,unu_1, \ldots, u_n and online vertices v1,…,vnv_1, \ldots, v_n, where vjv_j is adjacent to uj,uj+1,…,unu_j, u_{j+1}, \ldots, u_n. It has a perfect matching (vjv_j to uju_j), but greedy that prefers the last free neighbour matches vjv_j to un+1−ju_{n+1-j} and runs out after n/2n/2 arrivals. The maximum matching is computed by augmenting paths, the algorithm practised in Maximum Bipartite Matching.

python · try it yourself
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 12\frac{1}{2}, as usual for worst-case bounds.

cpp · try it yourself
#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 12\frac{1}{2}

Theorem. For every deterministic online algorithm and every even nn, there is an instance with a perfect matching of size nn on which the algorithm matches at most n/2n/2 vertices.

Proof

Work in pairs. For each pair of fresh offline vertices a,ba, b, an online vertex vv arrives adjacent to both. If the algorithm leaves vv unmatched, the next vertex of the pair is adjacent to aa only, and OPT matches both while the algorithm matches at most one. Otherwise it matches vv to one of them, say aa; the next online vertex v′v' is adjacent only to aa, so it cannot be matched. OPT matches vv to bb and v′v' to aa. Each pair contributes 2 to OPT and at most 1 to the algorithm.

The adversary must see the algorithm's choice before revealing v′v''s edges, which a deterministic algorithm cannot hide. The program builds this instance adaptively against three deterministic rules.

python · try it yourself
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 aa and bb was taken. The natural randomized algorithm, RANDOM, matches each arriving vertex to a uniformly random free neighbour. Surprisingly, it is still only 12+o(1)\frac{1}{2} + o(1)-competitive: Karp, Vazirani and Vazirani (1990) built instances on which RANDOM's expected matching is n2+O(log⁡n)\frac{n}{2} + O(\log n) out of nn. 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 (1−1/e)(1 - 1/e)-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 (1−1/e)(1 - 1/e)-competitive (Goel and Mehta, 2008); and with known i.i.d. arrivals, ratios above 1−1/e1 - 1/e are possible.

Test yourself

Why is every greedy algorithm for online bipartite matching 12\frac{1}{2}-competitive?

  1. It finds a maximum matching
  2. 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
  3. It is randomized
  4. It sees the whole graph

In the deterministic lower bound, what does the second online vertex of a pair look like?

  1. Adjacent to both offline vertices
  2. Adjacent only to the offline vertex the algorithm just used
  3. Adjacent to no vertex
  4. Adjacent to the unused offline vertex

What is the competitive ratio of RANDOM (a fresh uniformly random free neighbour at each arrival)?

  1. 1−1/e1 - 1/e
  2. 12+o(1)\frac{1}{2} + o(1)
  3. 11
  4. 3/43/4