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 of elements and a family of sets with costs are given; pick a subfamily of minimum total cost whose union is . When every element lies in at most sets, vertex cover is the special case (elements are edges, sets are the edges at a vertex).
The greedy algorithm is a -approximation, where . 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
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 CWith unit costs, line 3 picks the set covering the most uncovered elements. A straightforward implementation takes time per round and at most rounds; with buckets of sets by their current gain, the unweighted version runs in .
A direct proof for unit costs
Theorem. With unit costs, greedy uses at most sets, so it is an -approximation.
Proof. Let and the uncovered elements after rounds. The optimal sets cover , so one of them covers at least of its elements, and greedy covers at least as many:
After rounds at most elements are left, and each later round covers at least one, so at most more rounds follow. The total is at most .
The bound is even a little better than when OPT is large, because only the ratio enters. The exact 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 , where is the size of the largest set (the dual-fitting proof gives this sharper form).
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 elements in two rows of columns. The two rows are sets, so . Add "column blocks": block contains both rows of columns (numbering columns from 1), so it has elements. The largest block has elements, one more than a row, and greedy takes it. What remains is the same picture with , and greedy takes all blocks: a ratio of .
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 times a cover that costs , 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 instance above (62 elements, columns numbered from bit 0).
#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 -approximation for unless NP has quasi-polynomial algorithms; Feige (1998) raised the threshold to under the assumption NP DTIME; and Dinur and Steurer (2014) proved that is NP-hard for every , so it is impossible unless P = NP. Since greedy achieves , 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 sets, a different bound wins for small : LP rounding and the primal-dual method both give an -approximation (Rounding the Vertex Cover LP). For vertex cover () that is far better than .
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 of the uncovered elements, where ?
- Because every set has size at least
- Because the optimal sets cover all uncovered elements, so one of them covers at least a fraction, and greedy covers at least as many
- Because greedy chooses sets at random
- Because
In the two-row instance with column blocks, why does greedy start with the largest block?
- Because blocks are cheaper
- Because the largest block has elements, one more than a row of
- Because of the tie-breaking rule
- Because rows overlap
Which statement about the approximability of set cover is proved under P NP?
- Greedy is optimal
- No polynomial algorithm achieves for any constant (Dinur and Steurer, 2014)
- Set cover has a PTAS
- There is no -approximation