Module contents
Lesson 31 of 33Core 115 min

Approximation algorithms: greedy and LP rounding

When the optimum cannot be obtained, proximity can be guaranteed. Define approximation ratios and learn to bound the unknown optimum. Study 2-approximations for vertex cover via matching and linear relaxation rounding, greedy set cover with factor H_n and randomized rounding, metric traveling salesperson with doubled spanning tree and Christofides, k-center, and Graham's parallel machine scheduling.

After this lesson you can

  • Prove approximation factors by comparison with lower bounds on the optimum.
  • Design 2-approximations for vertex cover using matching and linear relaxation rounding.
  • Prove the H_n factor for greedy set cover and apply randomized rounding.
  • Implement doubled spanning tree and Christofides for metric traveling salesperson.
  • Analyze Gonzalez's k-center algorithm and Graham's scheduling and LPT.

Before you start

Motivation: guaranteeing quality without knowing the optimum

Three everyday engineering problems:

  • Deploy sensors. You have nn points to monitor and candidate locations, each with its cost and the set of points it reaches. Cover all points at minimum cost. If instead you have exactly kk sensors and want the worst-served point as close as possible to one, the problem changes shape but not difficulty.
  • Select tests. A continuous integration suite has hundreds of tests, each exercising a subset of project functions. Find the cheapest subset (by count or CI seconds) still exercising every function at least once.
  • Distribute jobs over a cluster. You have nn jobs of known duration and mm identical machines. Make the last job finish as early as possible.

All three are NP-hard. The first and second are set cover instances, which contain vertex cover from the independent-set family; the version with kk sensors is k-center, which contains dominating set; the third contains partition with m=2m = 2 and is strongly NP-hard when mm is part of the input. By NP-completeness theory, we do not expect an exact polynomial algorithm for any of them.

The previous lesson answered by giving up polynomial time: exact algorithms exploiting structure. This lesson gives up exactness, but not a guarantee. An approximation algorithm is polynomial and proves its solution is within a factor ρ\rho of the optimum on every input. The important word is “proves”: the optimum is unknown and the guarantee must come from reasoning that bounds it without computing it. The techniques are few and recur: greedy arguments compared with a combinatorial lower bound, linear relaxations rounded, and packing arguments. Everything that follows is a variation on that idea.

Approximation ratio and lower bounds on the optimum

Fix a minimization problem: each instance II has a set of feasible solutions, each solution SS has cost c(S)≥0c(S) \ge 0, and OPT(I)\mathrm{OPT}(I) is the minimum. Algorithm AA returns a feasible solution A(I)A(I).

Three nuances. This is a worst-case guarantee: an algorithm returning the optimum on 99.9 % of instances and 3 OPT3\,\mathrm{OPT} on the rest is a 3-approximation, not a 1.001-approximation. It is multiplicative: additive guarantees (c(A(I))≤OPT+kc(A(I)) \le \mathrm{OPT} + k) exist but are rare for NP-hard problems. And the factor is a property of the algorithm with its analysis, not the problem: the property of the problem is the best achievable factor, and determining that number occupies half the field.

The invisible optimum problem

To prove c(A(I))≤ρ OPT(I)c(A(I)) \le \rho\,\mathrm{OPT}(I) you cannot compute OPT(I)\mathrm{OPT}(I): if you could, approximation would not be needed. The pattern of almost all proofs is to find a quantity L(I)L(I) with two properties:

L(I)≤OPT(I)yc(A(I))≤ρ L(I).L(I) \le \mathrm{OPT}(I) \qquad\text{y}\qquad c(A(I)) \le \rho\, L(I).

Prove the first by looking at an arbitrary optimal solution without knowing it: “let S∗S^* be optimal; then S∗S^* must…”. Prove the second by looking at what the algorithm does. The art is choosing LL: too small and the second inequality fails; too large and the first is false. These are the ones used in the lesson:

ProblemLower bound L≤OPTL \le \mathrm{OPT}Why it is a boundFactor obtained
Vertex covermatching sizeevery matching edge needs its own vertex22
Weighted coverlinear relaxation optimum LP∗\mathrm{LP}^*every integer solution is fractional22
Set coverLP∗\mathrm{LP}^* (and prices bounding it)sameHn≈ln⁡nH_n \approx \ln n
Metric traveling salespersonminimum spanning tree; half a matchinga cycle minus one edge is a tree22 and 32\tfrac32
k-centerk+1k + 1 points separated by rrtwo share an optimal ball22
Scheduling on mm machinesmax⁡(∑jpj/m, max⁡jpj)\max(\sum_j p_j / m,\ \max_j p_j)some machine bears average load; the largest job goes whole2−1m2 - \tfrac1m and 43−13m\tfrac43 - \tfrac1{3m}

Each row is a section of the lesson. The ratio OPT/L\mathrm{OPT}/L on the worst instance limits what any analysis based on LL can prove; when LL is a relaxation value, that ratio has a name (the integrality gap) and you will see it live in the first figure.

How well can problems be approximated?

NP-hardness says nothing about approximability, and the problems here span the spectrum. Parallel-machine scheduling allows factors arbitrarily close to 1 (an approximation scheme, the subject of the next lesson). Vertex cover and k-center have factor 2: for k-center it is proved that no improvement is possible unless P = NP, and for cover this is conjectured. Set cover allows ln⁡n\ln n and no better. Traveling salesperson without the triangle inequality admits no constant factor. Lower bounds come from gap-preserving reductions and the PCP theorem, seen next lesson; here we prove only the two fitting in a paragraph (traveling salesperson and k-center) and cite the rest.

Vertex cover: maximal matching

A vertex cover of a graph G=(V,E)G = (V, E) is a S⊆VS \subseteq V touching every edge: for each uv∈Euv \in E, u∈Su \in S or v∈Sv \in S. Finding the smallest is NP-hard because its complement is a maximum independent set.

A matching M⊆EM \subseteq E is a set of edges with no common endpoints; it is maximal if no edge can be added (do not confuse with maximum, of largest cardinality, computed using augmenting paths in bipartite graphs and the blossom algorithm in general). A maximal matching is obtained greedily: traverse edges and retain each that shares no endpoint with those chosen.

Proof

Feasibility. If an edge uvuv had no endpoint in SS, it would share none with any edge of MM and could be added to MM, contradicting maximality.

Lower bound. Let S∗S^* be an optimal cover. Each edge of MM has an endpoint in S∗S^*, and as edges of MM share no endpoints, those vertices are distinct: ∣S∗∣≥∣M∣\abs{S^*} \ge \abs{M}. Therefore ∣S∣=2∣M∣≤2 OPT\abs{S} = 2\abs{M} \le 2\,\mathrm{OPT}.

∎

The lower bound is ∣M∣\abs{M}, and the analysis is tight: in complete bipartite Kn,nK_{n,n} any maximal matching is perfect, the algorithm returns all 2n2n vertices, and an optimal side has nn. Using a maximum rather than maximal matching does not help: Kn,nK_{n,n} is the same counterexample.

Can 2 be improved? Nobody knows how by a constant. Dinur and Safra (2005) proved that, unless P = NP, no factor better than 105−21≈1.360610\sqrt5 - 21 \approx 1.3606 exists; Khot, Minzer and Safra (2018) raised that bound to 2−ε\sqrt2 - \eps; and Khot and Regev (2008) proved that, if the unique games conjecture holds, no polynomial algorithm goes below 2−ε2 - \eps. The two-line algorithm would then be optimal.

Linear relaxation and rounding

Matching does not work if vertices have weights wv≥0w_v \ge 0: a vertex of weight 10001000 at an endpoint of an edge of MM is included anyway. The general tool is linear programming. Write the problem as an integer program with a variable xv∈{0,1}x_v \in \{0, 1\} per vertex and relax integrality, a convex relaxation:

OPT=min⁡ ∑vwvxvLP∗=min⁡ ∑vwvxvs. a.  xu+xv≥1∀ uv∈Es. a.  xu+xv≥1∀ uv∈Exv∈{0,1}0≤xv≤1.\begin{aligned} \mathrm{OPT} = \min\ & \textstyle\sum_{v} w_v x_v & \qquad\qquad \mathrm{LP}^* = \min\ & \textstyle\sum_{v} w_v x_v \\ \text{s. a. }\ & x_u + x_v \ge 1 \quad \forall\, uv \in E & \text{s. a. }\ & x_u + x_v \ge 1 \quad \forall\, uv \in E \\ & x_v \in \{0, 1\} & & 0 \le x_v \le 1. \end{aligned}

Every cover is a solution of the program on the right, so LP∗≤OPT\mathrm{LP}^* \le \mathrm{OPT}. This inequality is the lower bound, and it has an advantage matching lacked: it is computable in polynomial time, giving a numerical certificate of how far you can be from the optimum on your specific instance.

The fractional solution is not a cover, but can be rounded. This problem’s relaxation has a strong property proved in the previous lesson while constructing the linear kernel: its vertices have coordinates in {0,12,1}\{0, \tfrac12, 1\} (Nemhauser and Trotter, 1975; the proof does not use weights). Rounding does not need it, but it explains what the figure shows.

Proof

Feasibility. For each edge, xu+xv≥1x_u + x_v \ge 1, so max⁡(xu,xv)≥12\max(x_u, x_v) \ge \tfrac12 and one endpoint belongs to SS.

Cost. For v∈Sv \in S, 1≤2xv1 \le 2x_v. Then w(S)=∑v∈Swv≤∑v∈S2wvxv≤2∑v∈Vwvxv=2 LP∗w(S) = \sum_{v \in S} w_v \le \sum_{v \in S} 2 w_v x_v \le 2\sum_{v \in V} w_v x_v = 2\,\mathrm{LP}^*, where the last inequality uses wvxv≥0w_v x_v \ge 0.

∎

This is the linear relaxation rounding pattern: (1) formulate an integer program, (2) solve the relaxation, giving LP∗≤OPT\mathrm{LP}^* \le \mathrm{OPT}, (3) convert x\vb{x} into a feasible integer solution losing at most factor ρ\rho relative to ∑vwvxv\sum_v w_v x_v. Steps (2) and (3) are proved separately, and (3) always has two parts: feasibility and cost.

InteractiveVertex cover linear relaxation
½a½b½c½d½e½f½g½h1i0j
  • number = xvx_v; fill = vertex included
  • in rounding
  • in integer optimum
  • uncovered edge
LP*5OPT6rounding92 · LP*10
integer optimum
The integer optimum (dashed aquamarine) costs OPT=6\mathrm{OPT} = 6. The chain LP∗≤OPT≤rounding≤2 LP∗\mathrm{LP}^* \le \mathrm{OPT} \le \text{rounding} \le 2\,\mathrm{LP}^* holds: 5 ≤\le 6 ≤\le 9 ≤\le 10. The gap OPT/LP∗\mathrm{OPT}/\mathrm{LP}^* is 1.200: no analysis based only on LP∗\mathrm{LP}^* can guarantee less.
Graph
Rounding
Fractional optimum LP∗\mathrm{LP}^*55
Rounding9
Integer optimum6
Rounding / LP∗\mathrm{LP}^*1.801.80
Gap OPT/LP∗\mathrm{OPT} / \mathrm{LP}^*1.2001.200
Uncovered edges0
The figure starts at the last of four steps; replay it to see them: graph, relaxation optimum (blue intensity is xvx_v; thick edges are tight, with xu+xv=1x_u + x_v = 1), rounding at one half, and integer optimum. Bars compare LP∗\mathrm{LP}^*, OPT\mathrm{OPT}, rounding and 2 LP∗2\,\mathrm{LP}^*. The initial graph combines a triangle, a pentagon and a hub with one leaf, displaying all three values 0, ½ and 1. Try the bipartite graph (how many halves remain?), complete KnK_n while increasing nn (watch the gap), and ‘Umbral = 1’ (threshold = 1): the ‘rounding’ becomes cheaper and leaves edges uncovered.

In the initial graph, LP∗=5\mathrm{LP}^* = 5: half per vertex in the triangle (1.51.5) and pentagon (2.52.5), and 11 on the hub, with its leaf at 0. The integer optimum is 66 because a triangle needs 2 vertices and a pentagon 3, and the hub must be included to cover its leaf (or the leaf to cover it). Rounding includes the eight half-valued vertices and the hub: 9≤2 LP∗=109 \le 2\,\mathrm{LP}^* = 10. Chain 5≤6≤9≤105 \le 6 \le 9 \le 10 is exactly the theorem’s and teaches two things. First, rounding may be far from optimal (9/6=1.59/6 = 1.5) even when the relaxation is close (6/5=1.26/5 = 1.2): the loss comes from rounding, not the bound. Second, at ‘Umbral = 1’ the cost falls to 1 and appears better than optimal, but is not a cover. In the bipartite graph the relaxation is integral (total unimodularity of the bipartite incidence matrix, the same reason maximum flow has integer solutions), and the gap is 1.

In KnK_n the relaxation puts 12\tfrac12 at all vertices (LP∗=n/2\mathrm{LP}^* = n/2), while a cover needs n−1n - 1 vertices (omitting two leaves their edge uncovered). The gap is 2(n−1)/n=2−2/n2(n-1)/n = 2 - 2/n, tending to 2: no analysis using this relaxation can go below factor 2. To do so one would need to strengthen it with valid integer inequalities, e.g. ∑v∈Cxv≥∣C∣−1\sum_{v \in C} x_v \ge \abs{C} - 1 for each clique CC. Even that does not suffice in general: Charikar, Makarychev and Makarychev (2009) proved that the Sherali–Adams hierarchy, which systematically adds such inequalities, retains a gap of 2−ε2 - \eps after nδn^{\delta} rounds, with δ>0\delta > 0 depending on ε\eps.

Set cover

A universe UU of nn elements, a family S1,…,Sm⊆US_1, \dots, S_m \subseteq U whose union is UU, and costs cj≥0c_j \ge 0. A cover is a J⊆{1,…,m}J \subseteq \{1, \dots, m\} with ⋃j∈JSj=U\bigcup_{j \in J} S_j = U; the goal is minimum cost ∑j∈Jcj\sum_{j \in J} c_j. Vertex cover is the case where elements are edges and each vertex is the set of its incident edges: each element is in exactly two sets. Sensors and test selection are set covers directly.

Greedy and its prices

The greedy rule is the usual one in the greedy paradigm, with a well-chosen performance measure: at each step select the set with least cost per new element, cj/∣Sj∖C∣c_j / \abs{S_j \setminus C}, where CC is what is already covered. This is Johnson’s (1974) and Lovász’s (1975) greedy set cover for unit costs, and Chvátal’s (1979) for costs.

To analyze it, imagine greedy charges its cost to the elements it covers: if it chooses SjS_j and it covers kk new elements, each pays a price cj/kc_j/k. The sum of prices is exactly greedy’s cost, so it suffices to bound each price. Number elements e1,…,ene_1, \dots, e_n in coverage order (those in the same step in any order).

Part (b) follows by summing (a). The lemma is an averaging argument over sets in an optimal solution, which you will reconstruct step by step in the first guided exercise; first, the figure lets you see the inequality at every step.

InteractivePrices in greedy set cover
ABCDEFGHIJKLprice of each element, in order of coverage081stcovered element 24
  • chosen set (one color per step)
  • next choice
  • bound OPT/(n−k+1)\mathrm{OPT}/(n - k + 1)
  • label: letter and 1 / new
end
All covered with 9 sets at cost 9, exactly the sum of the 2424 prices. The optimum costs 8 (sets B, D, F, G, H, J, K, L, with “Show optimum”). The ratio is 1.13, below H24=3.78H_{24} = 3.78.
Instance
Greedy cost9
Optimum8
Final ratio1.13
HnH_n for nn elements3.78 (n = 24)
Maximum price / bound0.50
Above are points to monitor and disks for candidate sensors, with cost per new element beside each letter. The figure starts with greedy complete; replay it step by step. Each step chooses the set with the smallest figure (dashed border: next choice), colors it, and shares its cost among newly covered elements. Below are element prices in coverage order and, dashed, the lemma’s bound OPT/(n−k+1)\mathrm{OPT}/(n - k + 1): no bar exceeds it. Switch to ‘Instancia mala’ (bad instance) and increase kk: greedy prefers blocks to the two rows and its ratio grows like k/2k/2.

In the initial instance (24 points, 12 unit-cost disks), greedy uses 9 sensors and the brute-force optimum 8: ratio 1.1251.125, far from H24≈3.78H_{24} \approx 3.78. The bars remain far below the bound, and the largest price/bound ratio shown is a fraction of 1. ‘Instancia mala’ shows the logarithm is real: two rows AA and BB of 2k−12^k - 1 points and kk blocks S1,…,SkS_1, \dots, S_k of sizes 2,4,…,2k2, 4, \dots, 2^k crossing both rows. The optimum is {A,B}\{A, B\}, costing 2. But the largest block covers 2k2^k elements versus 2k−12^k - 1 for a row, so greedy prefers it; the same happens at every step, so it pays kk. With n=2k+1−2n = 2^{k+1} - 2 elements, the ratio is k/2≈12log⁡2nk/2 \approx \tfrac12\log_2 n. With costs exactly HnH_n is achieved: elements 1,…,n1, \dots, n, a singleton {i}\{i\} of cost 1/i1/i, and the entire universe costing 1+ε1 + \eps. When ii elements remain uncovered (the 1,…,i1, \dots, i), the cheapest singleton is {i}\{i\} with ratio 1/i1/i, beating the universe’s (1+ε)/i(1 + \eps)/i; greedy chooses it and continues, paying 1/n+⋯+1/1=Hn1/n + \cdots + 1/1 = H_n versus 1+ε1 + \eps; you will check this in the lab.

And essentially no better is possible. Feige (1998) proved approximating within (1−ε)ln⁡n(1 - \eps)\ln n would imply NP⊆DTIME(nO(log⁡log⁡n))\mathrm{NP} \subseteq \mathrm{DTIME}(n^{\bigO(\log\log n)}), and Dinur and Steurer (2014) obtained the same threshold under P ≠\neq NP. The three-line greedy algorithm is, up to lower-order terms, the best possible polynomial algorithm.

Prices as a dual solution

The lemma compares with OPT\mathrm{OPT}; a finer argument compares with LP∗\mathrm{LP}^* and gives a better bound for small sets. The set cover relaxation and its dual are

LP∗=min⁡∑jcjxj  s. a. ∑j:e∈Sjxj≥1  ∀e,  x≥0max⁡∑eye  s. a. ∑e∈Sjye≤cj  ∀j,  y≥0.\mathrm{LP}^* = \min \sum_j c_j x_j \ \ \text{s. a.}\ \sum_{j : e \in S_j} x_j \ge 1\ \ \forall e,\ \ x \ge 0 \qquad\qquad \max \sum_e y_e \ \ \text{s. a.}\ \sum_{e \in S_j} y_e \le c_j\ \ \forall j,\ \ y \ge 0.

By weak duality, any dual-feasible yy satisfies ∑eye≤LP∗≤OPT\sum_e y_e \le \mathrm{LP}^* \le \mathrm{OPT}. Prices are almost a dual solution: they can exceed a set’s cost. But only slightly.

Proof

Fix a set SjS_j with s≤ds \le d elements and order them a1,…,asa_1, \dots, a_s by when greedy covers them. Just before the step covering aia_i, elements ai,…,asa_i, \dots, a_s remain uncovered, so SjS_j offered at least s−i+1s - i + 1 new elements for cost cjc_j, and greedy chose something equally cheap or cheaper per element: precio(ai)≤cj/(s−i+1)\mathrm{precio}(a_i) \le c_j/(s - i + 1). Summing, ∑e∈Sjprecio(e)≤cjHs≤cjHd\sum_{e \in S_j}\mathrm{precio}(e) \le c_j H_s \le c_j H_d, the dual constraint of SjS_j for y=precio/Hdy = \mathrm{precio}/H_d. Since prices sum to greedy’s cost, that cost is Hd∑eye≤Hd LP∗H_d\sum_e y_e \le H_d\,\mathrm{LP}^*.

∎

This technique (the algorithm simultaneously constructs an integer solution and an “almost feasible” dual one, and the factor is how much to scale the dual) is called dual fitting, and leads to the primal-dual method in the next lesson. In vertex cover dd is maximum degree Δ\Delta, so greedily choosing a maximum-degree vertex is an HΔH_\Delta-approximation, and graphs exist where it loses a logarithmic factor: maximal matching, which looks more foolish, is better.

Frequency rounding and randomized rounding

Two ways to round the set cover relaxation complete the picture.

Threshold 1/f1/f. If each element belongs to at most ff sets, each constraint has at most ff variables summing to at least 1, so one is at least 1/f1/f. Selecting {j:xj≥1/f}\{j : x_j \ge 1/f\} is feasible and costs at most f LP∗f\,\mathrm{LP}^* by the same argument as vertex cover, the f=2f = 2 case. This is good when ff is small and useless otherwise.

Randomized rounding. Interpret xjx_j as a probability. Randomized rounding (Raghavan and Thompson, 1987) takes an optimal solution x\vb{x} and repeats tt independent rounds; in each, include each SjS_j with probability xjx_j.

Proof

Cost. In each round expected cost is ∑jcjxj=LP∗\sum_j c_j x_j = \mathrm{LP}^*; in tt rounds, at most t LP∗t\,\mathrm{LP}^* (a set selected twice is paid once). By Markov’s inequality, P(coste>4t LP∗)≤14\Pr(\text{coste} > 4t\,\mathrm{LP}^*) \le \tfrac14.

Coverage. An element ee remains uncovered in one round with probability ∏j:e∈Sj(1−xj)≤exp⁡(−∑j:e∈Sjxj)≤e−1\prod_{j : e \in S_j}(1 - x_j) \le \exp\big(-\sum_{j : e \in S_j} x_j\big) \le e^{-1}, using 1−z≤e−z1 - z \le e^{-z} and the constraint for ee. Rounds are independent, so it remains uncovered at the end with probability ≤e−t≤1/(4n)\le e^{-t} \le 1/(4n). By the union bound, some of the nn elements remains uncovered with probability ≤14\le \tfrac14.

The two bad events together have probability ≤12\le \tfrac12.

∎

If it fails, repeat: the expected attempts are at most 2 and the probability of failing rr times in a row is 2−r2^{-r}, the usual amplification. Checking feasibility and cost is trivial, so this is a Las Vegas algorithm. It can also be derandomized using conditional expectations.

Factor O(log⁡n)\bigO(\log n) is worse in its constant than greedy’s HnH_n. The interest is generality: it works with multicover constraints (≥be\ge b_e), capacity-limited sets or, in the original work, packet routing minimizing link congestion. There the relevant random variable is a sum of independent indicators (link load), and the tool is the multiplicative Chernoff bound combined with the union bound: if expected link load is μ≤1\mu \le 1, the Chernoff method gives P(X≥1+δ)≤eδ/(1+δ)1+δ\Pr(X \ge 1 + \delta) \le e^\delta/(1+\delta)^{1+\delta}, which with δ=Θ(log⁡n/log⁡log⁡n)\delta = \Theta(\log n/\log\log n) drops below 1/n21/n^2; the union bound over links closes the argument, and congestion is O(log⁡n/log⁡log⁡n)\bigO(\log n/\log\log n) times the fractional value.

Traveling salesperson: impossible in general, approximable with a metric

Traveling salesperson asks for a minimum-length Hamiltonian cycle in a complete graph with weights d(u,v)≥0d(u, v) \ge 0; its decision version is NP-complete because it contains Hamiltonian cycle. That reduction says something stronger.

The proof is a gap-creating reduction: instances from Hamiltonian graphs have optimum nn, and the others have optimum greater than ρn\rho n. You will do it in the third guided exercise. The ingredient needed to escape is the triangle inequality, d(u,w)≤d(u,v)+d(v,w)d(u, w) \le d(u, v) + d(v, w): traveling salesperson with it is metric traveling salesperson. Its key consequence is that shortcuts do not lengthen: if a closed walk visits all vertices, perhaps repeatedly, and you skip repeats, each shortcut replaces a path u→v1→⋯→vr→wu \to v_1 \to \cdots \to v_r \to w by edge u→wu \to w, no longer than the path.

The doubled spanning tree

An optimal Hamiltonian cycle without one edge is a spanning tree, so the minimum spanning tree TT (computed with Kruskal or Prim) satisfies w(T)≤OPTw(T) \le \mathrm{OPT}, with nonnegative weights. Double every edge of TT: all degrees are even and the multigraph is connected, so it has an Eulerian circuit of length 2w(T)2w(T) visiting every vertex. Shortcut repeats: the result is the preorder traversal of TT.

The proof is the previous three sentences in order; you will reconstruct it in the second guided exercise, including errors that arise when a hypothesis is skipped.

Christofides: fix only odd degrees

Doubling TT is wasteful: only odd-degree vertices prevent an Eulerian circuit and need fixing. Christofides (1976), independently Serdyukov (1978), observed it suffices to add a matching among them.

Proof

Let H∗H^* be an optimal cycle.

Tree. Removing an edge of H∗H^* leaves a spanning tree, so w(T)≤w(H∗)=OPTw(T) \le w(H^*) = \mathrm{OPT}.

Matching. Traverse H∗H^* and keep only vertices in OO, in order: by the triangle inequality, that cycle over OO has length at most OPT\mathrm{OPT}. Since ∣O∣\abs{O} is even, alternating edges divide into two perfect matchings of OO. Their weights sum to at most OPT\mathrm{OPT}, so the lighter weighs at most OPT/2\mathrm{OPT}/2, as does the minimum MM: w(M)≤OPT/2w(M) \le \mathrm{OPT}/2.

Circuit and shortcuts. T+MT + M is connected (it contains TT) and every vertex has even degree (those in OO gain one edge; the rest none). Its Eulerian circuit has length w(T)+w(M)≤32 OPTw(T) + w(M) \le \tfrac32\,\mathrm{OPT}, and shortcutting does not lengthen it by the triangle inequality.

∎

This is the central result of metric traveling salesperson approximation. Notice where each hypothesis is used: the triangle inequality appears twice (in the shortcut cycle over OO and in final shortcuts), and positive weights in the first bound.

InteractiveChristofides step by step
ABCDEFGHI
  • minimum spanning tree
  • odd degree and matching
  • Christofides tour
  • optimum
  • doubled tree
optimum
Christofides: 194.5194.5, or 1.061 OPT1.061\,\mathrm{OPT}, below 32 OPT=274.9\tfrac32\,\mathrm{OPT} = 274.9. The doubled tree (enable comparison) gives 253.0253.0, or 1.380 OPT1.380\,\mathrm{OPT}, with guarantee 2. Drag cities to seek the worst ratio: neither exceeds its bound.
Cities
9
w(T)w(T) versus OPT155.9 ≤ 183.3
w(M)/OPTw(M) / \mathrm{OPT} (bound ½)0.217
Christofides194.5
Christofides / OPT (bound 1.5)1.061
Doubled tree / OPT (bound 2)1.380
Optimum (Held–Karp)183.3
Nine cities with Euclidean distance. The figure starts at the result; replay or advance through steps to see construction: minimum spanning tree (blue), odd-degree vertices (orange rings), minimum perfect matching (orange), Eulerian circuit, shortcuts (dashed: new edges replacing repeated segments), and finally the exact optimum computed by Held–Karp. Readouts check w(T)≤OPTw(T) \le \mathrm{OPT}, w(M)≤OPT/2w(M) \le \mathrm{OPT}/2 and the final ratio live. Drag cities to seek the worst ratio you can, and activate comparison with the doubled tree. Try the circle: why does Christofides hit the optimum exactly?

In the initial instance, w(T)=155.9w(T) = 155.9, w(M)=39.7w(M) = 39.7 and Christofides has length 194.5194.5, versus optimum 183.3183.3: 1.061 OPT1.061\,\mathrm{OPT}. The doubled tree gives 253.0253.0, 1.380 OPT1.380\,\mathrm{OPT}. On the circle the minimum tree is a path around the contour, only its endpoints have odd degree, and the matching is the edge closing the contour: Christofides returns the optimum, while doubled-tree preorder, starting at an interior path vertex, usually has to retrace its steps (with nine cities, 1.195 OPT1.195\,\mathrm{OPT}; with five or six, preorder happens to be optimal).

For 45 years nobody improved 32\tfrac32 for general metric traveling salesperson. Karlin, Klein and Oveis Gharan (2021) reduced it to 32−ε\tfrac32 - \eps with ε>10−36\eps > 10^{-36}, replacing the minimum tree with a random tree drawn from the traveling salesperson linear relaxation: an important theoretical, not practical, advance. From below, Karpinski, Lampis and Schmied (2015) proved that approximating metric traveling salesperson within a factor below 123/122123/122 is NP-hard. The gap between 1.0081.008 and 1.51.5 remains open. In the Euclidean plane the situation is much better: an approximation scheme achieves 1+ε1 + \eps for any fixed ε>0\eps > 0 (Arora, 1998; Mitchell, 1999); schemes are the next lesson’s subject.

k-center: the farthest point

Given nn points with a distance dd satisfying the triangle inequality and integer kk, k-center seeks kk centers CC minimizing radius r(C)=max⁡vd(v,C)r(C) = \max_v d(v, C), where d(v,C)=min⁡c∈Cd(v,c)d(v, C) = \min_{c \in C} d(v, c): the worst distance from a point to its closest center. This is deployment of kk sensors, warehouses or service replicas when the worst case matters, not the mean.

Gonzalez’s algorithm (1985) is farthest-first traversal: choose any first center and, while there are fewer than kk, add the point farthest from the chosen centers. With precomputed distances it costs O(nk)\bigO(nk).

Proof

Let c1,…,ckc_1, \dots, c_k be centers in selection order and qq the final farthest point, with d(q,{c1,…,ck})=rd(q, \{c_1, \dots, c_k\}) = r.

Separation. When cjc_j (j≥2j \ge 2) was chosen, its distance to predecessors was Dj=d(cj,{c1,…,cj−1})D_j = d(c_j, \{c_1, \dots, c_{j-1}\}) and it was the farthest point. Each point’s distance to centers can only decrease when centers are added, so the final maximum rr does not exceed the maximum at that moment: r≤Djr \le D_j. Therefore d(ci,cj)≥Dj≥rd(c_i, c_j) \ge D_j \ge r for i<ji < j, and d(q,ci)≥rd(q, c_i) \ge r by definition of rr. The k+1k + 1 points c1,…,ck,qc_1, \dots, c_k, q are pairwise separated by at least rr.

Packing. An optimal solution has kk centers and every point is within ≤OPT\le \mathrm{OPT} of one. By the pigeonhole principle, two of those k+1k + 1 points, aa and bb, share an optimal center oo, and r≤d(a,b)≤d(a,o)+d(o,b)≤2 OPTr \le d(a, b) \le d(a, o) + d(o, b) \le 2\,\mathrm{OPT}.

∎

The lower bound here is not a relaxation but a packing: k+1k + 1 widely separated points force any solution with kk balls to have large radius. Factor 2 is the best possible:

Proof

Reduce from dominating set: given a graph G=(V,E)G = (V, E) and kk, is there D⊆VD \subseteq V with ∣D∣≤k\abs{D} \le k such that every vertex is in DD or adjacent to one in DD? It is NP-complete. Define d(u,v)=1d(u, v) = 1 if uv∈Euv \in E, d(u,v)=2d(u, v) = 2 if u≠vu \neq v are not adjacent, and d(v,v)=0d(v, v) = 0. This is a metric because 1+1≥21 + 1 \ge 2. If GG has a dominating set of size kk, k-center with centers in VV has radius 1; otherwise any choice of kk centers leaves a vertex at distance 2 and optimum is 2. A (2−ε)(2 - \eps)-approximation would return radius ≤2−ε<2\le 2 - \eps < 2, i.e. 1, in the first case and 2 in the second, deciding dominating set in polynomial time.

∎

These two theorems form k-center approximation: a two-line algorithm with the exact factor complexity allows. Hochbaum and Shmoys (1985) obtained the same factor with another algorithm based on trying candidate radii.

InteractiveThe farthest point
123
  • center (numbered by order) and its radius-rr ball
  • farthest point: center k+1k + 1
  • an optimum (radius OPT\mathrm{OPT})
With k=3k = 3 the Gonzalez radius is r=18.7r = 18.7. The 3 centers and farthest point (black ring) are separated by at least 18.7≥r18.7 \ge r. An optimum has only 33 balls, so one must contain two of those 4 points, whose distance is at most 2 OPT2\,\mathrm{OPT}: OPT≥r/2=9.3\mathrm{OPT} \ge r/2 = 9.3. The optimum with centers among the data points is 11.611.6: the ratio is 1.61≤21.61 \le 2.
Data
3
Gonzalez radius rr18.7
Lower bound r/2≤OPTr/2 \le \mathrm{OPT}9.3
Optimum (centers at data points)11.6
Ratio r/OPTr/\mathrm{OPT}1.61
Points in the plane with Gonzalez centers numbered in selection order and their balls of radius rr. Thin lines join the k+1k + 1 points of the proof (centers and farthest point, black ring): all are at least rr apart. Increase kk and watch each new center appear at the worst-served point. Change the first center and data, and activate an optimum (centers among points, by enumeration): ratio r/OPTr/\mathrm{OPT} never exceeds 2. With an outlier, what does the second center do?

With three groups and k=3k = 3, Gonzalez has radius 18.718.7 and optimum 11.611.6: ratio 1.611.61, not small. On real data Gonzalez often stays far from optimal, and its weakness appears with an outlier: the farthest point is, by construction, the rarest, and the algorithm devotes an entire center to it. This is not an analysis failure, because radius is the worst distance: if one isolated point matters as much as all others, the objective dictates this.

Relationship to k-means++

k-means++ initialization (Arthur and Vassilvitskii, 2007) is a randomized version of the same traversal: instead of the farthest point, it chooses each new center with probability proportional to d(x,C)2d(x, C)^2. The objective differs, k-means’ sum of squared distances rather than maximum, and sampling is exactly what it needs: far points are more likely, but a lone outlier weighs little against an entire group. Arthur and Vassilvitskii proved the expected cost of initial centers is at most 8(ln⁡k+2)8(\ln k + 2) times the k-means optimum, an expected O(log⁡k)\bigO(\log k)-approximation before any Lloyd iteration. Note d2d^2 is not a metric (it violates the triangle inequality, as just seen), so k-means++ analysis needs a relaxed form.

Parallel-machine scheduling

You have nn jobs with durations p1,…,pn>0p_1, \dots, p_n > 0 and mm identical machines. Each job runs whole on one machine, whose load is the sum of its jobs. The goal is to minimize makespan Cmax⁡C_{\max}, the largest load, i.e. the time the last job finishes (scheduling notation P∥Cmax⁡P \| C_{\max}). Two lower bounds are obvious: some machine bears at least the average, and the largest job runs whole on one machine:

OPT≥max⁡(1m∑jpj, max⁡jpj).\mathrm{OPT} \ge \max\Big(\frac{1}{m}\sum_j p_j,\ \max_j p_j\Big).

Graham’s (1966) list scheduling is the simplest conceivable greedy rule: traverse jobs in the given order and assign each to the currently least-loaded machine. With a load heap it costs O(nlog⁡m)\bigO(n\log m).

Proof

Let jj be a job finishing last, at time Cmax⁡=Sj+pjC_{\max} = S_j + p_j. When assigned, it went to the least-loaded machine, whose load was SjS_j; all others had load at least SjS_j, and all those loads consisted of jobs other than jj. Thus mSj≤∑i≠jpim S_j \le \sum_{i \neq j} p_i, and

Cmax⁡=Sj+pj≤1m∑i≠jpi+pj=1m∑ipi+(1−1m)pj≤OPT+(1−1m)OPT,C_{\max} = S_j + p_j \le \frac{1}{m}\sum_{i \ne j} p_i + p_j = \frac1m\sum_i p_i + \Big(1 - \frac1m\Big)p_j \le \mathrm{OPT} + \Big(1 - \frac1m\Big)\mathrm{OPT},

using the two lower bounds, one for each term.

∎

This is the list scheduling algorithm, and the proof shows where the loss arises: the last job, which may arrive when all machines are balanced. An instance of m(m−1)m(m - 1) unit jobs followed by one of size mm exploits this: the list distributes unit jobs (m−1m - 1 per machine) then adds the large one to a machine, Cmax⁡=2m−1C_{\max} = 2m - 1, while optimum puts the large one alone and units on the other m−1m - 1 machines, OPT=m\mathrm{OPT} = m. Ratio 2−1m2 - \tfrac1m exactly meets the bound. An important detail: list scheduling never looks at future jobs, so it is also an online algorithm with competitive ratio 2−1m2 - \tfrac1m.

LPT: largest first

If all jobs are known beforehand, the bad instance suggests a fix: prevent large jobs arriving last. LPT (longest processing time first) sorts jobs descending and applies list scheduling.

Proof

Number jobs in descending order, p1≥⋯≥pnp_1 \ge \cdots \ge p_n, and let ℓ\ell finish last. LPT assigns jobs 1,…,ℓ1, \dots, \ell identically with or without later ones, and removing jobs cannot increase optimum; so it suffices to prove the bound for instance p1,…,pℓp_1, \dots, p_\ell and its optimum OPT′≤OPT\mathrm{OPT}' \le \mathrm{OPT}. Call pℓp_\ell the smallest job, C=Sℓ+pℓC = S_\ell + p_\ell the LPT makespan, and OPT′\mathrm{OPT}' that instance’s optimum.

Case pℓ≤OPT′/3p_\ell \le \mathrm{OPT}'/3. Graham’s argument gives C≤OPT′+(1−1m)pℓ≤(1+13−13m)OPT′C \le \mathrm{OPT}' + (1 - \tfrac1m)p_\ell \le \big(1 + \tfrac13 - \tfrac1{3m}\big)\mathrm{OPT}'.

Case pℓ>OPT′/3p_\ell > \mathrm{OPT}'/3. Then every job exceeds OPT′/3\mathrm{OPT}'/3, and no optimal machine has three. We show LPT is optimal: suppose C>OPT′C > \mathrm{OPT}'. If any machine was empty when ℓ\ell was assigned, C=pℓ≤OPT′C = p_\ell \le \mathrm{OPT}'; so all had at least one job. Let aa count machines with exactly one; the other m−am - a had at least two, so ℓ−1≥a+2(m−a)=2m−a\ell - 1 \ge a + 2(m - a) = 2m - a. A machine with one job ii had load pi≥Sℓ>OPT′−pℓp_i \ge S_\ell > \mathrm{OPT}' - p_\ell: call a job large if pi>OPT′−pℓp_i > \mathrm{OPT}' - p_\ell; there are B≥aB \ge a. In the optimum, a large job cannot share a machine (any other job has size at least pℓp_\ell and the sum exceeds OPT′\mathrm{OPT}'), so occupies one alone, and the remaining ℓ−B\ell - B fit two per machine in the other m−Bm - B: ℓ−B≤2(m−B)\ell - B \le 2(m - B), i.e. ℓ≤2m−B≤2m−a≤ℓ−1\ell \le 2m - B \le 2m - a \le \ell - 1. Contradiction.

Tightness. With mm machines and jobs 2m−1,2m−1,2m−2,2m−2,…,m+1,m+1,m,m,m2m - 1, 2m - 1, 2m - 2, 2m - 2, \dots, m + 1, m + 1, m, m, m, the optimum pairs 2m−i2m - i with m+im + i (i=1,…,m−1i = 1, \dots, m - 1) and puts the three of size mm together: OPT=3m\mathrm{OPT} = 3m. LPT distributes the first 2m2m in pairs on each machine, all reach load 3m−13m - 1, and the final job of size mm finishes at 4m−14m - 1. The ratio is 4m−13m=43−13m\tfrac{4m-1}{3m} = \tfrac43 - \tfrac1{3m}.

∎
InteractiveGraham and LPT
M1M2M3M41111111111114bound 4 7
  • job (number is its size)
  • job finishing last
  • lower bound
  • optimum
end
Makespan 7, optimum 4: ratio 1.7501.750, with bound 1.7501.750. The job finishing last (orange, size 4) started at S=3S = 3, and until then all machines were busy, so S≤(∑p−4)/m=3S \le (\sum p - 4)/m = 3. Then Cmax⁡=S+p≤∑p/m+(1−1/m) p≤OPT+(1−1/m) pC_{\max} = S + p \le \sum p / m + (1 - 1/m)\,p \le \mathrm{OPT} + (1 - 1/m)\,p.
Instance
4
Order
Makespan7
Optimum4
Lower bound max⁡(∑p/m, pmax⁡)\max(\sum p/m,\ p_{\max})4
Final ratio1.750
Guarantee 2−1/m2 - 1/m1.750
A Gantt chart of assignments: each row is a machine and each block a job with its size. Replay job by job; at the end the job finishing last, used in the proof, is highlighted orange. The dashed line is bound max⁡(∑p/m,pmax⁡)\max(\sum p/m, p_{\max}) and aqua is optimum (branch and bound). The initial instance is bad for list scheduling: switch to ‘De mayor a menor’ (largest first) and watch the loss disappear. Then try the bad LPT instance and increase mm: the ratio approaches 4/34/3 without exceeding it.

With m=4m = 4, Graham’s instance gives makespan 7 by list versus optimum 4 (1.75=2−141.75 = 2 - \tfrac14), and LPT solves it exactly. The LPT instance with m=4m = 4 gives 15 versus 12, ratio 1.25=43−1121.25 = \tfrac43 - \tfrac1{12}. For this problem the story does not end at 43\tfrac43: Hochbaum and Shmoys (1987) gave an approximation scheme reaching 1+ε1 + \eps for any fixed ε>0\eps > 0, the central PTAS example of the next lesson.

Lab: approximations with measured guarantees

Time to measure. The cells implement each algorithm from scratch and compare it with the exact optimum on small instances, computed using the integer solver scipy.optimize.milp (HiGHS), Held–Karp (subset dynamic programming), or enumeration. Two things matter: no ratio exceeds its guarantee, and how far it typically stays from it.

[ ]Vertex cover: matching and linear relaxationBrowser
import numpy as np
import networkx as nx
from scipy.optimize import linprog, milp, LinearConstraint, Bounds

def vc_emparejamiento(n, aristas):
    """2-aproximación: los extremos de un emparejamiento maximal construido de forma voraz."""
    cubierto = np.zeros(n, dtype=bool)
    for u, v in aristas:
        if not cubierto[u] and not cubierto[v]:
            cubierto[u] = cubierto[v] = True
    return np.flatnonzero(cubierto)

def incidencia(n, aristas):
    A = np.zeros((len(aristas), n))
    for k, (u, v) in enumerate(aristas):
        A[k, u] = A[k, v] = 1
    return A

def vc_redondeo(n, aristas, w):
    """Relajación lineal con HiGHS y redondeo a 1/2, comprobando la factibilidad."""
    r = linprog(w, A_ub=-incidencia(n, aristas), b_ub=-np.ones(len(aristas)), bounds=(0, 1), method="highs")
    S = np.flatnonzero(r.x >= 0.5 - 1e-9)        # tolerancia: el solucionador puede devolver 0.4999999999
    dentro = np.zeros(n, dtype=bool); dentro[S] = True
    assert all(dentro[u] or dentro[v] for u, v in aristas), "el redondeo no es un recubrimiento"
    return S, r.fun, r.x

def vc_exacto(n, aristas, w):
    r = milp(w, constraints=LinearConstraint(incidencia(n, aristas), lb=1), integrality=np.ones(n), bounds=Bounds(0, 1))
    return r.fun

rng = np.random.default_rng(1)
r_emp, r_red, brecha, r_w, r_nx, valores = [], [], [], [], [], set()
for _ in range(30):
    n = 16
    E = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.25]
    uno = np.ones(n)
    opt = vc_exacto(n, E, uno)
    S2, lp, x = vc_redondeo(n, E, uno)
    valores |= {float(abs(round(t, 6))) for t in x}
    r_emp.append(len(vc_emparejamiento(n, E)) / opt)
    r_red.append(len(S2) / opt)
    brecha.append(opt / lp)
    w = rng.integers(1, 11, n).astype(float)    # con pesos, el emparejamiento ya no sirve
    S3, _, _ = vc_redondeo(n, E, w)
    opt_w = vc_exacto(n, E, w)
    r_w.append(w[S3].sum() / opt_w)
    G = nx.Graph(E); nx.set_node_attributes(G, dict(enumerate(w)), "w")
    S4 = nx.algorithms.approximation.min_weighted_vertex_cover(G, weight="w")
    r_nx.append(w[list(S4)].sum() / opt_w)

print("30 grafos G(16, 0.25):")
print(f"  emparejamiento / OPT:   media {np.mean(r_emp):.3f}, máximo {np.max(r_emp):.3f}")
print(f"  redondeo LP / OPT:      media {np.mean(r_red):.3f}, máximo {np.max(r_red):.3f}")
print(f"  OPT / LP* (brecha):     media {np.mean(brecha):.3f}, máximo {np.max(brecha):.3f}")
print(f"  con pesos, redondeo / OPT: media {np.mean(r_w):.3f}, máximo {np.max(r_w):.3f}")
print(f"  con pesos, networkx / OPT: media {np.mean(r_nx):.3f}, máximo {np.max(r_nx):.3f}")
print("  valores que toma x en las soluciones de HiGHS:", sorted(valores))

for n in [4, 6, 8, 10]:
    E = [(u, v) for u in range(n) for v in range(u + 1, n)]
    _, lp, _ = vc_redondeo(n, E, np.ones(n))
    opt = vc_exacto(n, E, np.ones(n))
    print(f"K_{n}: LP* = {lp:.1f}, OPT = {opt:.0f}, brecha = {opt / lp:.3f}")

Three observations. First: on these graphs the guarantee is not a pessimistic bound. Both algorithms reach exactly 2 on the worst of 30 graphs and lose nearly 60 % on average (1.5801.580 and 1.5931.593). Integer optimum is close to LP∗\mathrm{LP}^* (mean gap 1.1081.108, maximum 1.251.25), so the loss is rounding, which raises all halves to 1, as in the figure. Second: HiGHS returns values in {0,12,1}\{0, \tfrac12, 1\}, as half-integrality predicts, because its method ends at a polytope vertex. Third: with weights, rounding loses 53 % on average and the networkx function 41 %. That function implements another 2-approximation, Bar-Yehuda and Even’s (1985) local-ratio algorithm, without solving a linear program; same guarantee, different typical behavior. The gaps of KnK_n reproduce 2−2/n2 - 2/n.

[ ]Set cover: greedy, threshold 1/f and randomized roundingBrowser
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds

def voraz_cobertura(n, conjuntos, costes):
    """Chvátal: el conjunto de menor coste por elemento nuevo. Devuelve los elegidos, los precios y el orden."""
    sin_cubrir = set(range(n))
    elegidos, precio, orden = [], np.zeros(n), []
    while sin_cubrir:
        utiles = [i for i in range(len(conjuntos)) if conjuntos[i] & sin_cubrir]
        i = min(utiles, key=lambda i: costes[i] / len(conjuntos[i] & sin_cubrir))
        nuevos = conjuntos[i] & sin_cubrir
        for e in sorted(nuevos):
            precio[e] = costes[i] / len(nuevos)
            orden.append(e)
        sin_cubrir -= nuevos
        elegidos.append(i)
    return elegidos, precio, orden

def matriz(n, conjuntos):
    A = np.zeros((n, len(conjuntos)))
    for j, S in enumerate(conjuntos):
        A[list(S), j] = 1
    return A

def cobertura_lp(n, conjuntos, costes):
    r = linprog(costes, A_ub=-matriz(n, conjuntos), b_ub=-np.ones(n), bounds=(0, 1), method="highs")
    return r.x, r.fun

def cobertura_exacta(n, conjuntos, costes):
    r = milp(costes, constraints=LinearConstraint(matriz(n, conjuntos), lb=1),
             integrality=np.ones(len(conjuntos)), bounds=Bounds(0, 1))
    return r.fun

def redondeo_aleatorizado(n, conjuntos, x, rng, rondas):
    """t rondas; en cada una entra S_j con probabilidad x_j. Se repite hasta cubrir (Las Vegas)."""
    intentos = 0
    while True:
        intentos += 1
        elegido = np.zeros(len(conjuntos), dtype=bool)
        for _ in range(rondas):
            elegido |= rng.random(len(conjuntos)) < x
        if len(set().union(*(conjuntos[j] for j in np.flatnonzero(elegido)))) == n:
            return np.flatnonzero(elegido), intentos

def instancia_azar(n, m, rng):
    conjuntos = [set(rng.choice(n, size=rng.integers(3, 13), replace=False).tolist()) for _ in range(m)]
    for e in range(n):
        if not any(e in S for S in conjuntos):
            conjuntos[rng.integers(m)].add(e)
    costes = np.array([1.0 + 0.25 * len(S) + rng.random() for S in conjuntos])
    return conjuntos, costes

rng = np.random.default_rng(0)
n, m = 40, 30
rondas = int(np.ceil(np.log(4 * n)))
filas = []
for _ in range(12):
    C, c = instancia_azar(n, m, rng)
    opt = cobertura_exacta(n, C, c)
    x, lp = cobertura_lp(n, C, c)
    G, precio, orden = voraz_cobertura(n, C, c)
    lema = max(precio[e] * (n - k) / opt for k, e in enumerate(orden))   # k desde 0: cota OPT/(n - k)
    R, intentos = redondeo_aleatorizado(n, C, x, rng, rondas)
    f = int(matriz(n, C).sum(axis=1).max())
    U = np.flatnonzero(x >= 1 / f - 1e-9)
    filas.append((c[G].sum() / opt, c[R].sum() / opt, intentos, c[U].sum() / opt, opt / lp, lema, f))
F = np.array(filas)
print(f"12 instancias con n = {n} elementos y m = {m} conjuntos; redondeo con {rondas} rondas:")
print(f"  voraz / OPT:                 media {F[:, 0].mean():.3f}, máximo {F[:, 0].max():.3f}   (H_40 = {sum(1 / k for k in range(1, 41)):.2f})")
print(f"  redondeo aleatorizado / OPT: media {F[:, 1].mean():.3f}, máximo {F[:, 1].max():.3f}, intentos medios {F[:, 2].mean():.2f}")
print(f"  umbral 1/f / OPT:            media {F[:, 3].mean():.3f}, máximo {F[:, 3].max():.3f}   (f entre {F[:, 6].min():.0f} y {F[:, 6].max():.0f})")
print(f"  OPT / LP*:                   media {F[:, 4].mean():.3f}, máximo {F[:, 4].max():.3f}")
print(f"  lema: máximo de precio_k (n - k + 1) / OPT = {F[:, 5].max():.3f}")

for n in [10, 100]:      # la instancia ponderada en la que el voraz paga exactamente H_n
    C = [{e} for e in range(n)] + [set(range(n))]
    c = np.array([1 / (e + 1) for e in range(n)] + [1.001])
    G, _, _ = voraz_cobertura(n, C, c)
    print(f"instancia de H_n, n = {n}: voraz {c[G].sum():.4f}, OPT {cobertura_exacta(n, C, c):.4f}, H_n = {sum(1 / k for k in range(1, n + 1)):.4f}")

Greedy loses 13.5 % on average (22 % worst case) against a guarantee H40=4.28H_{40} = 4.28, and the lemma line confirms no price exceeds its bound (maximum 0.6020.602). Randomized rounding instead pays 1.891.89 times optimum on average, and threshold 1/f1/f with frequencies 9 to 14 pays 2.142.14 times: their guarantees are worse than greedy’s, and so is their behavior here. Randomized rounding losing to greedy is no contradiction: O(log⁡n)\bigO(\log n) with constant 4 is worse than HnH_n, and the algorithm as written includes many redundant sets (the next lab prunes them). The last line is the tight instance: greedy pays exactly HnH_n versus optimum 1.0011.001.

[ ]Metric traveling salesperson: doubled tree, Christofides and without a metricBrowser
import numpy as np
import networkx as nx

def distancias(P):
    return np.sqrt(((P[:, None, :] - P[None, :, :]) ** 2).sum(-1))

def prim(D):
    n = len(D)
    dentro = np.zeros(n, dtype=bool); dentro[0] = True
    mejor, padre, arbol = D[0].copy(), np.zeros(n, dtype=int), []
    for _ in range(n - 1):
        v = int(np.argmin(np.where(dentro, np.inf, mejor)))
        arbol.append((int(padre[v]), v)); dentro[v] = True
        cerca = D[v] < mejor
        mejor, padre = np.where(cerca, D[v], mejor), np.where(cerca, v, padre)
    return arbol

def longitud(ciclo, D):
    return sum(D[ciclo[i], ciclo[(i + 1) % len(ciclo)]] for i in range(len(ciclo)))

def atajar(paseo):
    visto, ciclo = set(), []
    for v in paseo:
        if v not in visto:
            visto.add(v); ciclo.append(v)
    return ciclo

def arbol_doblado(D):
    """El preorden del árbol mínimo es el circuito del árbol doblado ya atajado."""
    return list(nx.dfs_preorder_nodes(nx.Graph(prim(D)), 0))

def christofides(D):
    n = len(D)
    T = prim(D)
    grado = np.bincount(np.array(T).ravel(), minlength=n)
    impares = [v for v in range(n) if grado[v] % 2]
    K = nx.Graph()
    K.add_weighted_edges_from((u, v, D[u, v]) for i, u in enumerate(impares) for v in impares[i + 1:])
    M = nx.min_weight_matching(K)                 # perfecto: K es completo con un número par de vértices
    G = nx.MultiGraph(T); G.add_edges_from(M)
    ciclo = atajar([u for u, _ in nx.eulerian_circuit(G, source=0)])
    return ciclo, sum(D[u, v] for u, v in T), sum(D[u, v] for u, v in M)

def held_karp(D):
    """Óptimo exacto en O(2^n n^2): dp[S, j] = camino mínimo desde 0 que visita S y acaba en j."""
    n = len(D)
    N = 1 << (n - 1)
    dp = np.full((N, n - 1), np.inf)
    for j in range(n - 1):
        dp[1 << j, j] = D[0, j + 1]
    Dm = D[1:, 1:]
    for S in range(1, N):
        fuera = [k for k in range(n - 1) if not S >> k & 1]
        if fuera:
            cand = (dp[S][:, None] + Dm[:, fuera]).min(axis=0)
            for k, val in zip(fuera, cand):
                dp[S | 1 << k, k] = min(dp[S | 1 << k, k], val)
    return float((dp[N - 1] + D[1:, 0]).min())

rng = np.random.default_rng(2)
F = []
for _ in range(20):
    D = distancias(rng.random((9, 2)))
    opt = held_karp(D)
    c, wT, wM = christofides(D)
    F.append((longitud(arbol_doblado(D), D) / opt, longitud(c, D) / opt, wT / opt, wM / opt))
F = np.array(F)
print("20 instancias de 9 ciudades en el cuadrado unidad:")
for nombre, col in [("árbol doblado / OPT", 0), ("Christofides / OPT", 1), ("w(T) / OPT", 2), ("w(M) / OPT", 3)]:
    print(f"  {nombre:20s} media {F[:, col].mean():.3f}, máximo {F[:, col].max():.3f}")
ref = nx.approximation.christofides(nx.from_numpy_array(D))
print("networkx.approximation.christofides en la última instancia:", round(longitud(ref[:-1], D) / opt, 3),
      "  la nuestra:", round(F[-1, 1], 3))

for n in [8, 12, 16]:     # sin desigualdad triangular: distancia al cuadrado entre puntos de una recta
    x = np.arange(n, dtype=float)
    D2 = (x[:, None] - x[None, :]) ** 2
    print(f"{n} puntos en una recta con d = distancia²: árbol doblado / OPT = {longitud(arbol_doblado(D2), D2) / held_karp(D2):.2f}")

The analysis inequalities hold with room to spare: w(T)w(T) is around 70 % of optimum and w(M)w(M) less than half, so their sum w(T)+w(M)w(T) + w(M) is already usually above optimum, and shortcuts reduce the final ratio to a few percentage points. The doubled tree loses considerably more on average. The networkx implementation (same idea, its own tree and matching) matches ours on the last instance. With squared distances on a line the doubled tree exceeds 2 at 8 points and grows with nn: the minimum tree is the line (weight-1 edges), preorder from an endpoint traverses it and returns with a jump of weight (n−1)2(n-1)^2, and no theorem forbids it because the metric assumption is false.

[ ]k-center and scheduling: Gonzalez, list and LPT versus optimumBrowser
import itertools
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds

def gonzalez(D, k, primero=0):
    centros, dist = [primero], D[primero].copy()
    while len(centros) < k:
        c = int(np.argmax(dist))                  # el punto peor atendido pasa a ser centro
        centros.append(c)
        dist = np.minimum(dist, D[c])
    return centros, dist.max()

def kcentro_exacto(D, k):
    """Centros entre los propios puntos, enumerando los C(n, k) subconjuntos."""
    return min(D[list(C)].min(axis=0).max() for C in itertools.combinations(range(len(D)), k))

rng = np.random.default_rng(3)
cocientes = []
for _ in range(15):
    P = rng.random((16, 2))
    D = np.sqrt(((P[:, None] - P[None]) ** 2).sum(-1))
    for k in (2, 3, 4):
        _, r = gonzalez(D, k, primero=int(rng.integers(16)))
        cocientes.append(r / kcentro_exacto(D, k))
print(f"k-centro, 45 casos (16 puntos, k = 2, 3, 4): Gonzalez / OPT media {np.mean(cocientes):.3f}, máximo {np.max(cocientes):.3f}")

def lista(p, m):
    carga = np.zeros(m)
    for t in p:
        carga[np.argmin(carga)] += t
    return carga.max()

def lpt(p, m):
    return lista(sorted(p, reverse=True), m)

def makespan_exacto(p, m):
    """MILP: x[j, i] = 1 si el trabajo j va a la máquina i; C >= carga de cada máquina; minimizar C."""
    n = len(p)
    c = np.r_[np.zeros(n * m), 1.0]
    A1 = np.zeros((n, n * m + 1))
    for j in range(n):
        A1[j, j * m:(j + 1) * m] = 1
    A2 = np.zeros((m, n * m + 1))
    for i in range(m):
        A2[i, i:n * m:m] = p
        A2[i, -1] = -1
    r = milp(c, constraints=[LinearConstraint(A1, 1, 1), LinearConstraint(A2, -np.inf, 0)],
             integrality=np.r_[np.ones(n * m), 0], bounds=Bounds(0, np.r_[np.ones(n * m), np.inf]))
    return r.fun

F = []
for _ in range(20):
    m = int(rng.integers(2, 5))
    p = rng.integers(1, 21, size=10).astype(float)
    opt = makespan_exacto(p, m)
    F.append((lista(p, m) / opt, lpt(p, m) / opt, max(p.sum() / m, p.max()) / opt))
F = np.array(F)
print("planificación, 20 casos (10 trabajos, m de 2 a 4):")
print(f"  lista / OPT: media {F[:, 0].mean():.3f}, máximo {F[:, 0].max():.3f}")
print(f"  LPT / OPT:   media {F[:, 1].mean():.3f}, máximo {F[:, 1].max():.3f}")
print(f"  cota max(suma/m, p_max) / OPT: media {F[:, 2].mean():.3f}, mínimo {F[:, 2].min():.3f}")
for m in (3, 5):
    p = [m] * 3 + [s for s in range(m + 1, 2 * m) for _ in range(2)]
    print(f"instancia ajustada para LPT, m = {m}: LPT {lpt(p, m):.0f}, OPT {makespan_exacto(np.array(p, float), m):.0f}, "
          f"cociente {lpt(p, m) / makespan_exacto(np.array(p, float), m):.4f}, cota {4 / 3 - 1 / (3 * m):.4f}")

Gonzalez comes closest to its guarantee in practice: mean 1.3671.367 and one case 1.8881.888, because farthest-first traversal does not try to balance anything. List scheduling loses 12 % on average (33 % worst case), far from 2−1m2 - \tfrac1m but clearly above LPT, which loses 2 % on average and under 10 % in the worst case. The last line shows why both analyses work well here: bound max⁡(∑p/m,pmax⁡)\max(\sum p/m, p_{\max}) is within 4 % of optimum in every case. Tight instances reach exactly 43−13m\tfrac43 - \tfrac1{3m}.

Lab: minimum test selection

Now an applied case with library tools. A project has 400 functions in 20 modules of 20 and a test suite with three profiles generated by an explicit model: 220 unit tests exercising 3 to 8 functions from one module, taking 0.2 to 1 s; 60 integration tests exercising 5 to 12 functions from each of two modules, taking 2 to 8 s; and 12 end-to-end tests touching 8 modules, taking 30 to 90 s. Add one unit test for each function exercised by no test. Seek two things: the smallest number of tests exercising all functions, and the smallest CI time. Both are set covers.

[ ]Test selection: greedy, rounding and integer solverBrowser
import time
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
from scipy.sparse import csr_matrix

rng = np.random.default_rng(7)
MODULOS, POR_MODULO = 20, 20
F = MODULOS * POR_MODULO
def del_modulo(mod, k):
    return set((mod * POR_MODULO + rng.choice(POR_MODULO, size=k, replace=False)).tolist())

tests, coste, tipo = [], [], []
for _ in range(220):
    tests.append(del_modulo(rng.integers(MODULOS), rng.integers(3, 9))); coste.append(rng.uniform(0.2, 1.0)); tipo.append("unitario")
for _ in range(60):
    a, b = rng.choice(MODULOS, 2, replace=False)
    tests.append(del_modulo(a, rng.integers(5, 13)) | del_modulo(b, rng.integers(5, 13))); coste.append(rng.uniform(2, 8)); tipo.append("integración")
for _ in range(12):
    tests.append(set().union(*(del_modulo(md, rng.integers(4, 10)) for md in rng.choice(MODULOS, 8, replace=False))))
    coste.append(rng.uniform(30, 90)); tipo.append("e2e")
for f in sorted(set(range(F)) - set().union(*tests)):
    tests.append({f}); coste.append(rng.uniform(0.2, 1.0)); tipo.append("unitario")
coste = np.array(coste)
m = len(tests)
filas, cols = zip(*[(f, j) for j, S in enumerate(tests) for f in S])
A = csr_matrix((np.ones(len(filas)), (filas, cols)), shape=(F, m))
print(f"{F} funciones, {m} tests; cada función la ejecutan entre {A.sum(1).min():.0f} y {A.sum(1).max():.0f} tests")
print(f"ejecutar la suite entera: {coste.sum():.0f} s")

def voraz(c):
    sin, elegidos = set(range(F)), []
    while sin:
        j = min((j for j in range(m) if tests[j] & sin), key=lambda j: c[j] / len(tests[j] & sin))
        sin -= tests[j]; elegidos.append(j)
    return elegidos

def podar(elegidos, c):
    """Quita, del más caro al más barato, cada test cuyas funciones ya ejecutan los demás elegidos."""
    cuenta = np.asarray(A[:, elegidos].sum(axis=1)).ravel()
    sel = set(elegidos)
    for j in sorted(elegidos, key=lambda j: -c[j]):
        idx = list(tests[j])
        if (cuenta[idx] >= 2).all():
            cuenta[idx] -= 1; sel.discard(j)
    return sorted(sel)

def resolver(c, nombre):
    t = time.perf_counter(); G = voraz(c); tg = time.perf_counter() - t
    t = time.perf_counter(); lp = linprog(c, A_ub=-A, b_ub=-np.ones(F), bounds=(0, 1), method="highs"); tl = time.perf_counter() - t
    rondas = int(np.ceil(np.log(4 * F)))
    while True:
        elegido = np.zeros(m, dtype=bool)
        for _ in range(rondas):
            elegido |= rng.random(m) < lp.x
        if (A[:, np.flatnonzero(elegido)].sum(axis=1) > 0).all():
            break
    R = list(np.flatnonzero(elegido))
    t = time.perf_counter()
    ex = milp(c, constraints=LinearConstraint(A, lb=1), integrality=np.ones(m), bounds=Bounds(0, 1))
    te = time.perf_counter() - t
    opt = ex.fun
    print(f"\n{nombre}: LP* = {lp.fun:.2f}, OPT = {opt:.2f}, OPT / LP* = {opt / lp.fun:.3f}")
    for etiqueta, sol in [("voraz", G), ("voraz + poda", podar(G, c)), ("redondeo aleatorizado", R), ("redondeo + poda", podar(R, c))]:
        print(f"  {etiqueta:22s} {c[sol].sum():8.2f}  ({c[sol].sum() / opt:.3f} OPT, {len(sol)} tests)")
    print(f"  tiempos: voraz {1000 * tg:.0f} ms, LP {1000 * tl:.0f} ms, MILP {1000 * te:.0f} ms")
    return ex

resolver(np.ones(m), "mínimo número de tests")
ex = resolver(coste, "mínimo tiempo de CI (s)")
sel = np.flatnonzero(ex.x > 0.5)
print("\nselección óptima por tiempo, por tipo:", {t: int(sum(tipo[j] == t for j in sel)) for t in ("unitario", "integración", "e2e")})

What comes out, and why:

  • The relaxation is almost exact. OPT/LP∗\mathrm{OPT}/\mathrm{LP}^* is within 1.4 % in test count and 0.2 % in time. With a lower bound this close to optimum, the solver’s branch and bound discards almost every branch, and HiGHS proves optimality in a fraction of a second. Do not generalize: families with gap Θ(log⁡n)\Theta(\log n) exist and relaxation does not do that work there.
  • Greedy is good, and better with pruning. It loses 8 % in test count and 11 % in time, mainly because it initially chooses some slow test covering many functions that later becomes redundant. Pruning redundant tests, which does not alter the guarantee, brings it within 1 % of optimum.
  • Randomized rounding alone is bad; with pruning, competitive. Its 8 rounds include almost every set with xj>0x_j > 0, explaining the high test-count ratio. Pruned, it matches or beats pruned greedy.
  • The time-optimal selection has 78 unit tests, 5 integration and 3 end-to-end: a few slow tests pay off when they exercise many functions otherwise requiring many separate unit tests. It goes from 1194 s to 269 s CI.

Times printed by the cell vary by machine and run; the robust fact is the order of magnitude: all three methods finish in a fraction of a second with 400 functions. The practical lesson echoes optimization manuals: if the integer solver solves your instance, use it; an approximation algorithm helps when it cannot (millions of elements, streaming decisions, no commercial solver license) and, above all, LP∗\mathrm{LP}^* tells you in any case how much you may be losing.

Typical mistakes

Exercises

QuizIs it a lower bound on the optimum?
Which quantities are valid lower bounds on the optimum for every instance of the stated problem?

More than one answer may be correct.

QuizWhich is a 2-approximation?
Four unweighted vertex-cover algorithms. Which are 2-approximations on every graph?

More than one answer may be correct.

NumericThe integrality gap in K₂₅
Compute the integrality gap OPT/LP∗\mathrm{OPT}/\mathrm{LP}^* of the (unweighted) vertex-cover linear relaxation on complete graph K25K_{25}.
NumericHow many rounds of rounding?
In randomized rounding of a cover with n=1000n = 1000 elements, each remains uncovered in one round with probability at most e−1e^{-1}, and rounds are independent. What is the least number of rounds tt guaranteeing, by the union bound, that the probability of leaving any element uncovered is at most 0.10.1?
NumericLPT worst case with eight machines
With m=8m = 8 machines and Graham's tight instance for LPT (two jobs of each size 15,14,…,915, 14, \dots, 9 and three of size 88), what is the ratio between LPT makespan and optimum?
QuizWhy does the matching weigh half?
In Christofides' analysis, which argument correctly proves w(M)≤OPT/2w(M) \le \mathrm{OPT}/2?
QuizGonzalez with squared distances
You apply Gonzalez's algorithm to points using ‘distance’ d(u,v)=∥u−v∥2d(u, v) = \norm{u - v}^2 and compare with the k-center optimum for that same dd. What guarantee holds?
ProofGreedy set cover is an H_n-approximation
Prove: Let e1,…,ene_1, \dots, e_n be the order in which greedy covers elements and precio(ek)\mathrm{precio}(e_k) the cost of the set covering eke_k divided by its number of newly covered elements. Then precio(ek)≤OPT/(n−k+1)\mathrm{precio}(e_k) \le \mathrm{OPT}/(n - k + 1), and greedy costs at most Hn OPTH_n\,\mathrm{OPT}.
0
Fix kk and look just before the greedy step covering eke_k. Let RR be the set of still-uncovered elements.

Step 1 of 4. How many elements does RR have at least?

ProofThe doubled tree is a 2-approximation
Prove: In metric traveling salesperson, the cycle obtained by shortcutting the Eulerian circuit of the doubled minimum spanning tree has length at most 2 OPT2\,\mathrm{OPT}.
0
Let TT be a minimum spanning tree and H∗H^* an optimal Hamiltonian cycle.

Step 1 of 3. How do you relate w(T)w(T) to OPT\mathrm{OPT}?

ProofNonmetric traveling salesperson admits no constant factor
Prove: If for some constant ρ≥1\rho \ge 1 there is a polynomial ρ\rho-approximation for traveling salesperson with arbitrary nonnegative weights, then P = NP.
0
It suffices to decide the NP-complete Hamiltonian-cycle problem in polynomial time. You are given graph G=(V,E)G = (V, E) with nn vertices.

Step 1 of 3. What traveling-salesperson instance do you construct?

CodeImplement LPT
Implement lpt(p, m): it receives a list p of positive durations and a number of machines m, and returns (makespan, asignacion), where asignacion[j] is the machine (0 to m-1) of job j in the original order of p. Sort jobs largest first and assign each to the least-loaded machine, using a heap (heapq) for cost O(nlog⁡m)\bigO(n\log m). Tests check the assignment is valid, the makespan agrees with it, it reaches bound 43−13m\tfrac43 - \tfrac1{3m} on the tight instance, and never exceeds it against exact optimum on small instances.
import heapq

def lpt(p, m):
  """Devuelve (makespan, asignacion) del algoritmo LPT con m máquinas."""
  asignacion = [0] * len(p)          # tu código: ordenar por duración y usar un montículo de (carga, máquina)
  makespan = sum(p)
  return makespan, asignacion
Shift+Enter to run

Summary

Key idea
An approximation algorithm proves its ratio by comparing with a lower bound on the optimum that can be reasoned about without knowing it: a matching, linear relaxation, spanning tree, packing of separated points, or average load. Choosing that bound well is half the design.
  • The approximation ratio is a multiplicative worst-case guarantee valid for every instance; it says little about typical behavior, which must be measured.
  • Vertex cover: endpoints of a maximal matching and rounding the linear relaxation at 12\tfrac12 give factor 2. The integrality gap, 2−2/n2 - 2/n in KnK_n, prevents going below 2 with that relaxation, and under the unique games conjecture nobody can.
  • Set cover: greedy by cost per new element is an HnH_n-approximation (prices and averaging; with dual fitting, HdH_d versus LP∗\mathrm{LP}^*), and (1−ε)ln⁡n(1 - \eps)\ln n is NP-hard. Randomized rounding gives O(log⁡n)\bigO(\log n) using Markov and the union bound and generalizes to many more problems.
  • Traveling salesperson: without the triangle inequality no constant factor exists unless P = NP; with it the doubled tree gives 2 and Christofides 32\tfrac32, because the matching of odd vertices weighs at most half optimum.
  • k-center: Gonzalez farthest-first gives 2 by a packing argument, and 2−ε2 - \eps is NP-hard. k-means++ is its randomized version for another objective.
  • Scheduling: Graham list scheduling gives 2−1m2 - \tfrac1m even online; LPT gives 43−13m\tfrac43 - \tfrac1{3m}, and both bounds are tight.
  • In practice compute LP∗\mathrm{LP}^*: it certifies how much you may be losing and, if the relaxation is tight, an integer solver may give the optimum directly.