TExcelTAD
Home › Approximation Algorithms › Greedy Set Cover

Greedy Set Cover

Set cover generalizes vertex cover and dozens of practical problems: choose test cases that exercise every code path, sensors that watch every area, servers that host every service. A universe UU of nn elements and a family of sets S1,…,Sm⊆US_1, \ldots, S_m \subseteq U with costs wj≥0w_j \ge 0 are given; pick a subfamily of minimum total cost whose union is UU. When every element lies in at most ff sets, vertex cover is the special case f=2f = 2 (elements are edges, sets are the edges at a vertex).

The greedy algorithm is a HnH_n-approximation, where Hn=1+12+⋯+1n≤1+ln⁡nH_n = 1 + \frac{1}{2} + \cdots + \frac{1}{n} \le 1 + \ln n. The proof for weighted set cover by dual fitting is in Dual Fitting: Greedy Set Cover and the Harmonic Bound; this lesson gives a second, more direct proof for the unweighted case, shows a natural instance on which greedy loses a logarithmic factor, and explains why nothing polynomial can do substantially better.

The algorithm

text
GREEDY-SET-COVER(U, sets, w)
1  C = empty, R = U                         -- R holds the uncovered elements
2  while R is not empty
3      choose j minimizing  w_j / |S_j ∩ R|  -- cost per newly covered element
4      C = C + {j};  R = R - S_j
5  return C

With unit costs, line 3 picks the set covering the most uncovered elements. A straightforward implementation takes O(mn)O(mn) time per round and at most min⁡(m,n)\min(m, n) rounds; with buckets of sets by their current gain, the unweighted version runs in O(∑j∣Sj∣)O(\sum_j \lvert S_j \rvert).

A direct proof for unit costs

Theorem. With unit costs, greedy uses at most OPT⋅(1+ln⁡nOPT)+1\text{OPT} \cdot (1 + \ln \frac{n}{\text{OPT}}) + 1 sets, so it is an O(log⁡n)O(\log n)-approximation.

Proof. Let k=OPTk = \text{OPT} and RtR_t the uncovered elements after tt rounds. The kk optimal sets cover RtR_t, so one of them covers at least ∣Rt∣/k\lvert R_t \rvert / k of its elements, and greedy covers at least as many:

∣Rt+1∣≤(1−1k)∣Rt∣≤e−1/k∣Rt∣,so∣Rt∣≤n e−t/k.\lvert R_{t+1} \rvert \le \left(1 - \frac{1}{k}\right)\lvert R_t \rvert \le e^{-1/k}\lvert R_t \rvert, \qquad \text{so} \qquad \lvert R_t \rvert \le n\, e^{-t/k} .

After t=⌈kln⁡nk⌉t = \lceil k \ln \frac{n}{k} \rceil rounds at most kk elements are left, and each later round covers at least one, so at most kk more rounds follow. The total is at most kln⁡nk+1+kk \ln \frac{n}{k} + 1 + k. □\square

The bound is even a little better than Hn⋅OPTH_n \cdot \text{OPT} when OPT is large, because only the ratio nOPT\frac{n}{\text{OPT}} enters. The exact HnH_n bound, also for weighted sets, comes from the pricing argument of the dual-fitting lesson.

The program compares greedy with the exact optimum on random instances. The right column shows the guarantee HdH_d, where dd is the size of the largest set (the dual-fitting proof gives this sharper form).

python · try it yourself
import random
from itertools import combinations

def greedy(n, sets):
    R, chosen = set(range(n)), []
    while R:
        j = max(range(len(sets)), key=lambda j: (len(sets[j] & R), -j))
        chosen.append(j)
        R -= sets[j]
    return chosen

def optimum(n, sets):
    for k in range(1, len(sets) + 1):
        for C in combinations(range(len(sets)), k):
            if len(set().union(*(sets[j] for j in C))) == n:
                return k

rng = random.Random(2)
print(" n   m  greedy  OPT  ratio  H_d")
for _ in range(6):
    n, m = rng.randint(12, 18), rng.randint(8, 12)
    sets = [set(rng.sample(range(n), rng.randint(2, 6))) for _ in range(m)]
    for e in range(n):                                   # make sure a cover exists
        if not any(e in S for S in sets):
            rng.choice(sets).add(e)
    g, o = len(greedy(n, sets)), optimum(n, sets)
    d = max(len(S) for S in sets)
    print(f"{n:2} {m:3} {g:7} {o:4} {g / o:6.2f} {sum(1 / i for i in range(1, d + 1)):5.2f}")
 n   m  greedy  OPT  ratio  H_d
18   8       5    5   1.00  2.59
18  12       6    5   1.20  2.45
13   9       4    4   1.00  2.45
13   8       5    5   1.00  2.45
13  11       4    4   1.00  2.45
14   8       5    4   1.25  2.45

A logarithmic loss

Arrange n=2(2k−1)n = 2(2^k - 1) elements in two rows of 2k−12^k - 1 columns. The two rows are sets, so OPT=2\text{OPT} = 2. Add kk "column blocks": block ii contains both rows of columns 2i−1,…,2i−12^{i-1}, \ldots, 2^i - 1 (numbering columns from 1), so it has 2i2^i elements. The largest block has 2k2^k elements, one more than a row, and greedy takes it. What remains is the same picture with k−1k - 1, and greedy takes all kk blocks: a ratio of k2≈12log⁡2n\frac{k}{2} \approx \frac{1}{2}\log_2 n.

python · try it yourself
def instance(k):
    cols = 2 ** k - 1
    rows = [{(r, c) for c in range(1, cols + 1)} for r in range(2)]
    blocks = [{(r, c) for r in range(2) for c in range(2 ** (i - 1), 2 ** i)} for i in range(1, k + 1)]
    return rows + blocks

def greedy(U, sets):
    R, chosen = set(U), []
    while R:
        j = max(range(len(sets)), key=lambda j: (len(sets[j] & R), -j))
        chosen.append(j)
        R -= sets[j]
    return chosen

for k in range(2, 8):
    sets = instance(k)
    U = set().union(*sets)
    g = greedy(U, sets)
    print(f"k = {k}: n = {len(U):3}, greedy {len(g)} sets ({sum(j >= 2 for j in g)} blocks), OPT 2, ratio {len(g) / 2}")
k = 2: n =   6, greedy 2 sets (2 blocks), OPT 2, ratio 1.0
k = 3: n =  14, greedy 3 sets (3 blocks), OPT 2, ratio 1.5
k = 4: n =  30, greedy 4 sets (4 blocks), OPT 2, ratio 2.0
k = 5: n =  62, greedy 5 sets (5 blocks), OPT 2, ratio 2.5
k = 6: n = 126, greedy 6 sets (6 blocks), OPT 2, ratio 3.0
k = 7: n = 254, greedy 7 sets (7 blocks), OPT 2, ratio 3.5

With weights, the singleton instance of the dual-fitting lesson makes greedy pay exactly HnH_n times a cover that costs 1+ε1 + \varepsilon, so the analysis is tight in the weighted case as well.

In C++

Unweighted greedy with sets stored as 64-bit masks, run on the k=5k = 5 instance above (62 elements, columns numbered from bit 0).

cpp · try it yourself
#include <bit>
#include <cstdint>
#include <cstdio>
#include <vector>

int main() {
    const int k = 5, cols = (1 << k) - 1;            // 31 columns, two rows
    auto bit = [&](int row, int col) { return std::uint64_t(1) << (row * cols + col - 1); };
    std::vector<std::uint64_t> sets;
    for (int r = 0; r < 2; r++) {
        std::uint64_t s = 0;
        for (int c = 1; c <= cols; c++) s |= bit(r, c);
        sets.push_back(s);
    }
    for (int i = 1; i <= k; i++) {
        std::uint64_t s = 0;
        for (int c = 1 << (i - 1); c < (1 << i); c++) s |= bit(0, c) | bit(1, c);
        sets.push_back(s);
    }
    std::uint64_t uncovered = 0;
    for (auto s : sets) uncovered |= s;
    int rounds = 0;
    while (uncovered) {
        int best = 0;
        for (int j = 1; j < (int)sets.size(); j++)
            if (std::popcount(sets[j] & uncovered) > std::popcount(sets[best] & uncovered)) best = j;
        std::printf("round %d: set %d covers %d new elements\n", ++rounds, best, std::popcount(sets[best] & uncovered));
        uncovered &= ~sets[best];
    }
    std::printf("greedy uses %d sets, OPT uses 2\n", rounds);
}
round 1: set 6 covers 32 new elements
round 2: set 5 covers 16 new elements
round 3: set 4 covers 8 new elements
round 4: set 3 covers 4 new elements
round 5: set 2 covers 2 new elements
greedy uses 5 sets, OPT uses 2

Greedy is essentially optimal

The logarithm is not an artefact of the algorithm. Lund and Yannakakis (1994) showed that set cover has no clog⁡2nc \log_2 n-approximation for c<14c < \frac{1}{4} unless NP has quasi-polynomial algorithms; Feige (1998) raised the threshold to (1−ε)ln⁡n(1 - \varepsilon)\ln n under the assumption NP ⊈\not\subseteq DTIME(nO(log⁡log⁡n))(n^{O(\log \log n)}); and Dinur and Steurer (2014) proved that (1−ε)ln⁡n(1 - \varepsilon)\ln n is NP-hard for every ε>0\varepsilon > 0, so it is impossible unless P = NP. Since greedy achieves Hn≤ln⁡n+1H_n \le \ln n + 1, the approximability of set cover is known up to lower-order terms. The reductions behind these results are discussed in Tight Thresholds: MAX-3SAT, Clique and Set Cover.

When every element belongs to at most ff sets, a different bound wins for small ff: LP rounding and the primal-dual method both give an ff-approximation (Rounding the Vertex Cover LP). For vertex cover (f=2f = 2) that is far better than HnH_n.

Tip: In practice greedy set cover is a strong baseline: its typical ratio on real instances is close to 1, and lazy evaluation (keep sets in a priority queue keyed by their last known gain, and recompute only the top one) makes it fast on millions of elements. Gains only shrink, so a stale key is an upper bound and the recomputed top is correct.

Test yourself

In the direct proof for unit costs, why does each greedy round cover at least 1k\frac{1}{k} of the uncovered elements, where k=OPTk = \text{OPT}?

  1. Because every set has size at least nk\frac{n}{k}
  2. Because the kk optimal sets cover all uncovered elements, so one of them covers at least a 1k\frac{1}{k} fraction, and greedy covers at least as many
  3. Because greedy chooses sets at random
  4. Because Hn≤ln⁡n+1H_n \le \ln n + 1

In the two-row instance with kk column blocks, why does greedy start with the largest block?

  1. Because blocks are cheaper
  2. Because the largest block has 2k2^k elements, one more than a row of 2k−12^k - 1
  3. Because of the tie-breaking rule
  4. Because rows overlap

Which statement about the approximability of set cover is proved under P ≠\ne NP?

  1. Greedy is optimal
  2. No polynomial algorithm achieves (1−ε)ln⁡n(1 - \varepsilon)\ln n for any constant ε>0\varepsilon > 0 (Dinur and Steurer, 2014)
  3. Set cover has a PTAS
  4. There is no O(log⁡n)O(\log n)-approximation