TExcelTAD
Home › Approximation Algorithms › Mini Project: A Set Cover and Facility Location Toolkit

Mini Project: A Set Cover and Facility Location Toolkit

Approximation guarantees are worst-case promises. In practice you also want to know how far a particular answer is from optimal, and which of several algorithms to trust on your kind of instances. In this project you build a small toolkit that runs the main algorithms of the course on weighted set cover and on uncapacitated facility location, computes the exact optimum with an integer programming solver on small instances, and reports two numbers for every run: the true ratio ALGOPT\frac{\text{ALG}}{\text{OPT}} and the certified ratio ALGlower bound\frac{\text{ALG}}{\text{lower bound}}, which the algorithm can compute by itself without knowing OPT.

The steps:

  1. Generate instances and compute OPT (with milp) and the LP bound.
  2. Greedy set cover with a dual-fitting certificate.
  3. LP rounding: threshold and randomized.
  4. Primal-dual with a cleanup pass.
  5. Compare all set cover algorithms over many instances.
  6. Facility location: exact, LP, and greedy over stars.
  7. Facility location with the Jain-Vazirani primal-dual algorithm.
  8. Port the primal-dual set cover algorithm to C++.

Each step is a complete program; later steps repeat the pieces they need.

Step 1: Instances, OPT and the LP bound

A weighted set cover instance has nn elements, mm sets and weights. SciPy's milp solves the integer program min⁡∑jwjxj\min \sum_j w_j x_j subject to ∑j∋exj≥1\sum_{j \ni e} x_j \ge 1, x∈{0,1}mx \in \{0, 1\}^m exactly (by branch and bound with HiGHS), and linprog solves its relaxation. The ratio OPTLP\frac{\text{OPT}}{\text{LP}} shows how much room the LP leaves for rounding.

python · try it yourself
import random
import numpy as np
from scipy.optimize import Bounds, LinearConstraint, linprog, milp

def instance(seed, n=20, m=15):
    rng = random.Random(seed)
    sets = [set(rng.sample(range(n), rng.randint(3, 7))) for _ in range(m)]
    for e in range(n):
        if not any(e in S for S in sets):
            sets[rng.randrange(m)].add(e)
    return n, sets, [rng.randint(1, 9) for _ in range(m)]

def matrix(n, sets):
    return np.array([[1.0 if e in S else 0.0 for S in sets] for e in range(n)])

def exact(n, sets, w):
    res = milp(c=w, constraints=LinearConstraint(matrix(n, sets), lb=1), integrality=np.ones(len(sets)), bounds=Bounds(0, 1))
    return round(float(res.fun)), [j for j in range(len(sets)) if res.x[j] > 0.5]

def lp(n, sets, w):
    res = linprog(w, A_ub=-matrix(n, sets), b_ub=-np.ones(n), bounds=[(0, 1)] * len(sets), method="highs")
    return float(res.fun), [float(v) for v in res.x]

for seed in range(4):
    n, sets, w = instance(seed)
    opt, chosen = exact(n, sets, w)
    val, _ = lp(n, sets, w)
    f = max(sum(e in S for S in sets) for e in range(n))
    print(f"seed {seed}: OPT {opt:2} with sets {chosen}, LP {val:6.3f}, OPT/LP {opt / val:.3f}, max frequency f = {f}")
seed 0: OPT 24 with sets [4, 5, 6, 8, 13, 14], LP 24.000, OPT/LP 1.000, max frequency f = 6
seed 1: OPT 29 with sets [0, 3, 7, 9, 10, 11], LP 28.000, OPT/LP 1.036, max frequency f = 8
seed 2: OPT 13 with sets [3, 4, 7, 9, 13], LP 13.000, OPT/LP 1.000, max frequency f = 9
seed 3: OPT 24 with sets [1, 4, 5, 6, 10, 12, 14], LP 23.500, OPT/LP 1.021, max frequency f = 6

Step 2: Greedy with a dual-fitting certificate

Greedy charges each newly covered element the chosen set's cost per new element. The prices sum to the cost of the cover, and dividing them by the worst overcharge α=max⁡S1wS∑e∈Sprice(e)\alpha = \max_S \frac{1}{w_S}\sum_{e \in S} \text{price}(e) makes them a feasible dual, hence a lower bound on OPT (Dual Fitting: Greedy Set Cover and the Harmonic Bound). So every run certifies its own ratio α\alpha, which is at most HdH_d.

python · try it yourself
import random
from fractions import Fraction as F

def instance(seed, n=20, m=15):
    rng = random.Random(seed)
    sets = [set(rng.sample(range(n), rng.randint(3, 7))) for _ in range(m)]
    for e in range(n):
        if not any(e in S for S in sets):
            sets[rng.randrange(m)].add(e)
    return n, sets, [rng.randint(1, 9) for _ in range(m)]

def greedy(n, sets, w):
    R, chosen, price = set(range(n)), [], {}
    while R:
        j = min((j for j in range(len(sets)) if sets[j] & R), key=lambda j: (F(w[j], len(sets[j] & R)), j))
        for e in sets[j] & R:
            price[e] = F(w[j], len(sets[j] & R))
        chosen.append(j)
        R -= sets[j]
    alpha = max(sum(price[e] for e in S) / w[j] for j, S in enumerate(sets))
    return chosen, sum(w[j] for j in chosen), sum(price.values()) / alpha, alpha

for seed in range(4):
    n, sets, w = instance(seed)
    chosen, cost, bound, alpha = greedy(n, sets, w)
    d = max(len(S) for S in sets)
    print(f"seed {seed}: greedy cost {cost:2}, dual bound {float(bound):6.3f}, certified ratio {float(alpha):.3f} <= H_{d} = {float(sum(F(1, i) for i in range(1, d + 1))):.3f}")
seed 0: greedy cost 28, dual bound 15.849, certified ratio 1.767 <= H_7 = 2.593
seed 1: greedy cost 32, dual bound 19.200, certified ratio 1.667 <= H_7 = 2.593
seed 2: greedy cost 17, dual bound  9.520, certified ratio 1.786 <= H_7 = 2.593
seed 3: greedy cost 26, dual bound 12.857, certified ratio 2.022 <= H_7 = 2.593

Compare the dual bounds with the OPT values of step 1: the certificate is weaker than OPT, but it is available without solving anything.

Step 3: LP rounding

Two roundings of the LP solution (Rounding the Vertex Cover LP, Randomized Rounding for Set Cover):

  • threshold: take every set with xj∗≥1fx^*_j \ge \frac{1}{f}; an ff-approximation;
  • randomized: take set jj with probability min⁡(1,αxj∗)\min(1, \alpha x^*_j), then fix any uncovered element with its cheapest set; with α=ln⁡n\alpha = \ln n this is O(log⁡n)O(\log n) in expectation. The program averages 100 runs for α=1\alpha = 1 (one round, relying on fix-ups) and for α=ln⁡n\alpha = \ln n.

Both are measured against the LP value, which is their natural certificate.

python · try it yourself
import math
import random
import numpy as np
from scipy.optimize import linprog

def instance(seed, n=20, m=15):
    rng = random.Random(seed)
    sets = [set(rng.sample(range(n), rng.randint(3, 7))) for _ in range(m)]
    for e in range(n):
        if not any(e in S for S in sets):
            sets[rng.randrange(m)].add(e)
    return n, sets, [rng.randint(1, 9) for _ in range(m)]

def lp(n, sets, w):
    A = -np.array([[1.0 if e in S else 0.0 for S in sets] for e in range(n)])
    res = linprog(w, A_ub=A, b_ub=-np.ones(n), bounds=[(0, 1)] * len(sets), method="highs")
    return float(res.fun), [float(v) for v in res.x]

def fix_up(n, sets, w, chosen):
    covered = set().union(*(sets[j] for j in chosen))
    for e in range(n):
        if e not in covered:
            j = min((j for j in range(len(sets)) if e in sets[j]), key=lambda j: (w[j], j))
            chosen.add(j)
            covered |= sets[j]
    return chosen

def threshold(n, sets, w, x):
    f = max(sum(e in S for S in sets) for e in range(n))
    return {j for j in range(len(sets)) if x[j] >= 1 / f - 1e-9}

def randomized(n, sets, w, x, rng, alpha):
    chosen = {j for j in range(len(sets)) if rng.random() < min(1, alpha * x[j])}
    return fix_up(n, sets, w, chosen)

rng = random.Random(99)
for seed in range(4):
    n, sets, w = instance(seed)
    val, x = lp(n, sets, w)
    t = sum(w[j] for j in threshold(n, sets, w, x))
    r1 = sum(sum(w[j] for j in randomized(n, sets, w, x, rng, 1)) for _ in range(100)) / 100
    rl = sum(sum(w[j] for j in randomized(n, sets, w, x, rng, math.log(n))) for _ in range(100)) / 100
    print(f"seed {seed}: LP {val:6.3f}, threshold {t / val:.2f} x LP, randomized alpha = 1: {r1 / val:.2f} x LP, alpha = ln n: {rl / val:.2f} x LP")
seed 0: LP 24.000, threshold 1.29 x LP, randomized alpha = 1: 1.11 x LP, alpha = ln n: 1.29 x LP
seed 1: LP 28.000, threshold 1.32 x LP, randomized alpha = 1: 1.13 x LP, alpha = ln n: 1.32 x LP
seed 2: LP 13.000, threshold 1.00 x LP, randomized alpha = 1: 1.00 x LP, alpha = ln n: 1.00 x LP
seed 3: LP 23.500, threshold 1.23 x LP, randomized alpha = 1: 1.07 x LP, alpha = ln n: 1.23 x LP

When the LP solution is integral, every rounding returns it. With α=ln⁡n≈3\alpha = \ln n \approx 3, every set with xj∗≥0.34x^*_j \ge 0.34 is taken with certainty, and on these instances that reproduces threshold rounding exactly. A single round (α=1\alpha = 1) that relies on the fix-ups is cheaper here, although its expected cost has no O(log⁡n)O(\log n) guarantee in general: the fix-ups can be expensive.

Step 4: Primal-dual with a cleanup pass

The primal-dual algorithm raises the dual variable of an uncovered element until some set containing it becomes tight, and takes all tight sets (The Primal-Dual Method for Vertex Cover). The cover costs at most ff times the dual. A cleanup pass then removes chosen sets in reverse order whenever the rest still covers everything; it can only lower the cost, and the dual certificate stays valid.

python · try it yourself
import random

def instance(seed, n=20, m=15):
    rng = random.Random(seed)
    sets = [set(rng.sample(range(n), rng.randint(3, 7))) for _ in range(m)]
    for e in range(n):
        if not any(e in S for S in sets):
            sets[rng.randrange(m)].add(e)
    return n, sets, [rng.randint(1, 9) for _ in range(m)]

def primal_dual(n, sets, w):
    slack, y, chosen = list(w), [0] * n, []
    covered = set()
    for e in range(n):
        if e in covered:
            continue
        containing = [j for j in range(len(sets)) if e in sets[j]]
        y[e] = min(slack[j] for j in containing)
        for j in containing:
            slack[j] -= y[e]
            if slack[j] == 0 and j not in chosen:
                chosen.append(j)
                covered |= sets[j]
    return chosen, sum(y)

def cleanup(n, sets, chosen):
    kept = list(chosen)
    for j in reversed(chosen):
        rest = [k for k in kept if k != j]
        if len(set().union(*(sets[k] for k in rest))) == n:
            kept = rest
    return kept

for seed in range(4):
    n, sets, w = instance(seed)
    chosen, dual = primal_dual(n, sets, w)
    kept = cleanup(n, sets, chosen)
    f = max(sum(e in S for S in sets) for e in range(n))
    a, b = sum(w[j] for j in chosen), sum(w[j] for j in kept)
    print(f"seed {seed}: dual {dual:2}, primal-dual {a:2} ({len(chosen)} sets), after cleanup {b:2} ({len(kept)} sets), certified {b / dual:.2f} <= f = {f}")
seed 0: dual 22, primal-dual 35 (8 sets), after cleanup 24 (6 sets), certified 1.09 <= f = 6
seed 1: dual 24, primal-dual 38 (7 sets), after cleanup 29 (6 sets), certified 1.21 <= f = 8
seed 2: dual 13, primal-dual 18 (7 sets), after cleanup 13 (5 sets), certified 1.00 <= f = 9
seed 3: dual 15, primal-dual 27 (8 sets), after cleanup 24 (7 sets), certified 1.60 <= f = 6

Step 5: The comparison

Now all the set cover algorithms run on 8 instances (randomized rounding as a single round with fix-ups), and the table reports ALGOPT\frac{\text{ALG}}{\text{OPT}} for each, with the worst and average ratios at the bottom.

python · try it yourself
import random
from fractions import Fraction as F
import numpy as np
from scipy.optimize import Bounds, LinearConstraint, linprog, milp

def instance(seed, n=20, m=15):
    rng = random.Random(seed)
    sets = [set(rng.sample(range(n), rng.randint(3, 7))) for _ in range(m)]
    for e in range(n):
        if not any(e in S for S in sets):
            sets[rng.randrange(m)].add(e)
    return n, sets, [rng.randint(1, 9) for _ in range(m)]

def cover_cost(n, sets, w, chosen):
    assert len(set().union(*(sets[j] for j in chosen))) == n
    return sum(w[j] for j in chosen)

def greedy(n, sets, w):
    R, chosen = set(range(n)), []
    while R:
        j = min((j for j in range(len(sets)) if sets[j] & R), key=lambda j: (F(w[j], len(sets[j] & R)), j))
        chosen.append(j)
        R -= sets[j]
    return chosen

def lp(n, sets, w):
    A = -np.array([[1.0 if e in S else 0.0 for S in sets] for e in range(n)])
    return [float(v) for v in linprog(w, A_ub=A, b_ub=-np.ones(n), bounds=[(0, 1)] * len(sets), method="highs").x]

def threshold(n, sets, w):
    x, f = lp(n, sets, w), max(sum(e in S for S in sets) for e in range(n))
    return [j for j in range(len(sets)) if x[j] >= 1 / f - 1e-9]

def randomized(n, sets, w, rng):
    x = lp(n, sets, w)
    chosen = {j for j in range(len(sets)) if rng.random() < x[j]}        # one round, alpha = 1
    covered = set().union(*(sets[j] for j in chosen))
    for e in range(n):
        if e not in covered:
            j = min((j for j in range(len(sets)) if e in sets[j]), key=lambda j: (w[j], j))
            chosen.add(j)
            covered |= sets[j]
    return sorted(chosen)

def primal_dual(n, sets, w):
    slack, chosen, covered = list(w), [], set()
    for e in range(n):
        if e not in covered:
            containing = [j for j in range(len(sets)) if e in sets[j]]
            y = min(slack[j] for j in containing)
            for j in containing:
                slack[j] -= y
                if slack[j] == 0 and j not in chosen:
                    chosen.append(j)
                    covered |= sets[j]
    for j in reversed(list(chosen)):
        rest = [k for k in chosen if k != j]
        if len(set().union(*(sets[k] for k in rest))) == n:
            chosen = rest
    return chosen

def opt(n, sets, w):
    A = np.array([[1.0 if e in S else 0.0 for S in sets] for e in range(n)])
    return round(float(milp(c=w, constraints=LinearConstraint(A, lb=1), integrality=np.ones(len(sets)), bounds=Bounds(0, 1)).fun))

rng = random.Random(7)
names = ["greedy", "threshold", "one round", "primal-dual"]
ratios = {a: [] for a in names}
print("seed  OPT   " + "  ".join(f"{a:>11}" for a in names))
for seed in range(8):
    n, sets, w = instance(seed)
    o = opt(n, sets, w)
    costs = [cover_cost(n, sets, w, greedy(n, sets, w)), cover_cost(n, sets, w, threshold(n, sets, w)),
             cover_cost(n, sets, w, randomized(n, sets, w, rng)), cover_cost(n, sets, w, primal_dual(n, sets, w))]
    for a, c in zip(names, costs):
        ratios[a].append(c / o)
    print(f"{seed:4} {o:4}   " + "  ".join(f"{c / o:11.3f}" for c in costs))
print("worst      " + "  ".join(f"{max(ratios[a]):11.3f}" for a in names))
print("average    " + "  ".join(f"{sum(ratios[a]) / len(ratios[a]):11.3f}" for a in names))
seed  OPT        greedy    threshold    one round  primal-dual
   0   24         1.167        1.292        1.042        1.000
   1   29         1.103        1.276        1.069        1.000
   2   13         1.308        1.000        1.000        1.000
   3   24         1.083        1.208        1.000        1.000
   4   16         1.188        1.000        1.000        1.250
   5   23         1.174        1.478        1.261        1.609
   6   22         1.000        1.000        1.000        1.091
   7   19         1.000        1.737        1.105        1.053
worst            1.308        1.737        1.261        1.609
average          1.128        1.249        1.060        1.125

The guarantees rank the algorithms as greedy (HdH_d) and randomized rounding (O(log⁡n)O(\log n)) against threshold rounding and primal-dual (ff), but on these instances the observed ratios are all far below their bounds, and the ranking in practice depends on the instance family. The worst-case theory tells you what can go wrong; measurements tell you what usually does.

Step 6: Facility location as set cover

Uncapacitated facility location is a set cover problem in disguise: a star (i,S)(i, S) is a facility ii together with a set SS of clients, of cost fi+∑j∈Scijf_i + \sum_{j \in S} c_{ij}, and a solution is a cover of the clients by stars. Greedy over stars (Hochbaum, 1982) repeatedly picks the star of least cost per newly served client, and once facility ii is open its opening cost drops to 0. For each facility, the best star is found by sorting the remaining clients by distance and trying every prefix, so each round takes polynomial time even though there are exponentially many stars. The general guarantee is O(log⁡n)O(\log n); in metric instances it does much better.

python · try it yourself
import random
import numpy as np
from scipy.optimize import Bounds, LinearConstraint, linprog, milp

def ufl_instance(seed, nf=6, nc=14):
    rng = random.Random(seed)
    fac = [(rng.randint(0, 30), rng.randint(0, 30)) for _ in range(nf)]
    cli = [(rng.randint(0, 30), rng.randint(0, 30)) for _ in range(nc)]
    f = [rng.randint(10, 40) for _ in range(nf)]
    c = [[abs(a[0] - b[0]) + abs(a[1] - b[1]) for b in cli] for a in fac]
    return f, c

def ufl_model(f, c):
    nf, nc = len(f), len(c[0])
    cost = np.array(f + [c[i][j] for i in range(nf) for j in range(nc)], dtype=float)
    rows, lb = [], []
    for j in range(nc):                                  # sum_i x_ij >= 1
        r = np.zeros(nf + nf * nc); r[[nf + i * nc + j for i in range(nf)]] = 1; rows.append(r); lb.append(1)
    for i in range(nf):
        for j in range(nc):                              # y_i - x_ij >= 0
            r = np.zeros(nf + nf * nc); r[i] = 1; r[nf + i * nc + j] = -1; rows.append(r); lb.append(0)
    return cost, np.array(rows), np.array(lb, dtype=float)

def ufl_opt_and_lp(f, c):
    cost, A, lb = ufl_model(f, c)
    opt = milp(c=cost, constraints=LinearConstraint(A, lb=lb), integrality=np.ones(len(cost)), bounds=Bounds(0, 1)).fun
    lpv = linprog(cost, A_ub=-A, b_ub=-lb, bounds=[(0, 1)] * len(cost), method="highs").fun
    return round(float(opt)), float(lpv)

def greedy_stars(f, c):
    nf, nc = len(f), len(c[0])
    opening, unserved, total, opened = list(f), set(range(nc)), 0, []
    while unserved:
        best = None
        for i in range(nf):
            order = sorted(unserved, key=lambda j: (c[i][j], j))
            acc = opening[i]
            for k, j in enumerate(order, 1):
                acc += c[i][j]
                if best is None or acc / k < best[0]:
                    best = (acc / k, i, order[:k], acc)
        _, i, S, acc = best
        total += acc
        if opening[i]:
            opened.append(i)
        opening[i] = 0
        unserved -= set(S)
    return total, opened

for seed in range(5):
    f, c = ufl_instance(seed)
    opt, lpv = ufl_opt_and_lp(f, c)
    g, opened = greedy_stars(f, c)
    print(f"seed {seed}: LP {lpv:7.2f}, OPT {opt:4}, greedy stars {g:4} (ratio {g / opt:.3f}), opened {opened}")
seed 0: LP  200.00, OPT  200, greedy stars  201 (ratio 1.005), opened [1, 5, 2]
seed 1: LP  196.00, OPT  196, greedy stars  201 (ratio 1.026), opened [0, 2, 1, 3]
seed 2: LP  246.00, OPT  246, greedy stars  261 (ratio 1.061), opened [0, 4]
seed 3: LP  193.00, OPT  194, greedy stars  197 (ratio 1.015), opened [2, 3, 1]
seed 4: LP  245.00, OPT  245, greedy stars  273 (ratio 1.114), opened [0]

Step 7: Facility location by primal-dual

The Jain-Vazirani algorithm (Uncapacitated Facility Location) grows client budgets, opens facilities when they are paid for, and then keeps a non-conflicting subset. Its dual sum is a lower bound, so it certifies a ratio at most 3 on every run.

python · try it yourself
import random
from fractions import Fraction as Fr
from itertools import combinations

def ufl_instance(seed, nf=6, nc=14):
    rng = random.Random(seed)
    fac = [(rng.randint(0, 30), rng.randint(0, 30)) for _ in range(nf)]
    cli = [(rng.randint(0, 30), rng.randint(0, 30)) for _ in range(nc)]
    f = [rng.randint(10, 40) for _ in range(nf)]
    c = [[abs(a[0] - b[0]) + abs(a[1] - b[1]) for b in cli] for a in fac]
    return f, c

def jain_vazirani(f, c):
    F, D = range(len(f)), range(len(c[0]))
    v, frozen, opened, t = {}, set(), {}, Fr(0)
    paid = lambda i, t: sum(max(0, (v[j] if j in frozen else t) - c[i][j]) for j in D)
    while len(frozen) < len(D):
        cands = [Fr(c[i][j]) for i in F for j in D if j not in frozen and c[i][j] > t]
        for i in F:
            if i not in opened:
                rate = sum(1 for j in D if j not in frozen and c[i][j] <= t)
                if rate:
                    cands.append(t + (f[i] - paid(i, t)) / rate)
        t = min(cands)
        for i in F:
            if i not in opened and paid(i, t) >= f[i]:
                opened[i] = t
        for j in D:
            if j not in frozen and any(c[i][j] <= t for i in opened):
                frozen.add(j)
                v[j] = t
    I = []
    for i in sorted(opened, key=lambda i: (opened[i], i)):
        if all(not any(v[j] > c[i][j] and v[j] > c[k][j] for j in D) for k in I):
            I.append(i)
    cost = sum(f[i] for i in I) + sum(min(c[i][j] for i in I) for j in D)
    return cost, sum(v.values())

def brute_force(f, c):
    F, D = range(len(f)), range(len(c[0]))
    return min(sum(f[i] for i in S) + sum(min(c[i][j] for i in S) for j in D) for k in range(1, len(f) + 1) for S in combinations(F, k))

for seed in range(5):
    f, c = ufl_instance(seed)
    cost, dual = jain_vazirani(f, c)
    opt = brute_force(f, c)
    print(f"seed {seed}: dual {float(dual):7.2f}, OPT {opt:4}, Jain-Vazirani {cost:4} (true ratio {cost / opt:.3f}, certified {float(cost / dual):.3f} <= 3)")
seed 0: dual  197.33, OPT  200, Jain-Vazirani  207 (true ratio 1.035, certified 1.049 <= 3)
seed 1: dual  194.60, OPT  196, Jain-Vazirani  204 (true ratio 1.041, certified 1.048 <= 3)
seed 2: dual  243.00, OPT  246, Jain-Vazirani  246 (true ratio 1.000, certified 1.012 <= 3)
seed 3: dual  188.80, OPT  194, Jain-Vazirani  213 (true ratio 1.098, certified 1.128 <= 3)
seed 4: dual  245.00, OPT  245, Jain-Vazirani  245 (true ratio 1.000, certified 1.000 <= 3)

With only 6 facilities, brute force over the 26−12^6 - 1 sets of open facilities is as good as milp and confirms the optima of step 6. A complete toolkit would now put greedy stars and Jain-Vazirani side by side and report, for each instance, the best solution found and the best certified lower bound: the dual of Jain-Vazirani, or better still the LP value.

Step 8: In C++

The primal-dual set cover algorithm with cleanup, printing its certificate, on a fixed instance (sets as bit masks over 12 elements).

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

int main() {
    const int n = 12;
    std::vector<unsigned> sets = {0b000000001111, 0b000011110000, 0b111100000000, 0b001001001001,
                                  0b010010010010, 0b100100100100, 0b000000110011, 0b110011000000};
    std::vector<int> w = {4, 5, 4, 3, 3, 3, 2, 2};
    int m = sets.size();
    std::vector<int> slack = w, chosen;
    unsigned covered = 0;
    int dual = 0;
    for (int e = 0; e < n; e++) {
        if (covered >> e & 1) continue;
        int y = 1 << 30;
        for (int j = 0; j < m; j++) if (sets[j] >> e & 1) y = std::min(y, slack[j]);
        dual += y;
        for (int j = 0; j < m; j++)
            if (sets[j] >> e & 1) {
                slack[j] -= y;
                bool already = false;
                for (int k : chosen) if (k == j) already = true;
                if (slack[j] == 0 && !already) { chosen.push_back(j); covered |= sets[j]; }
            }
    }
    auto cost = [&](const std::vector<int>& S) { int s = 0; for (int j : S) s += w[j]; return s; };
    std::printf("primal-dual picks %zu sets, cost %d, dual %d\n", chosen.size(), cost(chosen), dual);
    for (int idx = (int)chosen.size() - 1; idx >= 0; idx--) {      // cleanup in reverse order
        unsigned rest = 0;
        for (int k = 0; k < (int)chosen.size(); k++) if (k != idx) rest |= sets[chosen[k]];
        if (std::popcount(rest) == n) chosen.erase(chosen.begin() + idx);
    }
    std::printf("after cleanup: sets");
    for (int j : chosen) std::printf(" %d", j);
    std::printf(", cost %d, certified ratio %.3f (f = 2)\n", cost(chosen), (double)cost(chosen) / dual);
}
primal-dual picks 5 sets, cost 14, dual 7
after cleanup: sets 6 3 7 5, cost 10, certified ratio 1.429 (f = 2)

Where to go next

  • Add local search for facility location (open, close or swap one facility while the cost drops): it is a (3+ε)(3 + \varepsilon)-approximation in the metric case (Arya, Garg, Khandekar, Meyerson, Munagala and Pandit, 2004) and often the best in practice.
  • Replace brute force by milp everywhere and scale the instances up until the exact solver struggles; plot the certified ratios as the instances grow.
  • Add the dual fitting analysis of greedy facility location (Jain, Mahdian, Markakis, Saberi and Vazirani, 2003) as a certificate for step 6.

Test yourself

What is the difference between the true ratio and the certified ratio reported by the toolkit?

  1. There is none
  2. The true ratio divides by OPT, which needs an exact solver; the certified ratio divides by a lower bound (a dual or the LP) that the algorithm computes itself, so it is at least the true ratio
  3. The certified ratio is always 2
  4. The true ratio is an upper bound on the certified one

Why can the cleanup pass after primal-dual never hurt the guarantee?

  1. Because it adds sets
  2. It only removes sets while the rest still covers all elements, so the cost can only drop and the dual stays a valid lower bound
  3. Because it re-solves the LP
  4. Because cleanup makes the dual larger

How does greedy over stars find the best star for a facility without enumerating all subsets of clients?

  1. It picks one client at a time at random
  2. For a fixed facility, the best star of each size takes the nearest clients, so it sorts the clients by distance and tries every prefix
  3. It solves an LP
  4. It uses dynamic programming over subsets