Module contents
Lesson 32 of 33Advanced 115 min

Approximation schemes, primal-dual method and hardness of approximation

Some problems can be approximated arbitrarily closely while others cannot pass a threshold. Construct the knapsack FPTAS by scaling and rounding, study primal-dual methods and guaranteed local search, and examine the other side: the PCP theorem, gap reductions, Håstad and Feige's optimal thresholds, the unique games conjecture and semidefinite programs.

After this lesson you can

  • Construct a knapsack FPTAS and prove its ratio and cost.
  • Design primal-dual algorithms and analyze them with relaxed complementary slackness.
  • Analyze local-search algorithms with approximation guarantees.
  • Explain the PCP theorem and its equivalence to MAX-3SAT inapproximability.
  • Place problems in the approximability landscape (FPTAS, PTAS, APX, log n, inapproximable) and explain the unique games conjecture.

Before you start

Motivation: not all NP-hard problems are equally hard

For NP-completeness theory, knapsack, vertex cover, set cover and traveling salesperson are alike: problems to which SAT reduces. For someone solving them on Monday morning they are worlds apart. With knapsack you can request a solution at 99.9 %99.9\,\% of optimum and obtain it in polynomial time. With vertex cover, nobody knows how to guarantee less than twice optimum. Set cover remains at factor ln⁡n\ln n. Traveling salesperson without the triangle inequality admits no reasonable factor, not even 2n2^n.

The previous lesson introduced the basics: approximation ratio, greedy algorithms and linear-program rounding. This lesson covers the whole spectrum in both directions:

  • Upwards, algorithms. Schemes approaching the optimum as closely as desired (knapsack FPTAS, scheduling PTAS), the primal-dual method converting linear duality into fast combinatorial algorithms, guaranteed local search, and Goemans–Williamson semidefinite programs.
  • Downwards, impossibility. Gap reductions, the PCP theorem explaining why many problems cannot be approximated beyond a constant, Håstad’s and Feige’s exact thresholds, and the unique games conjecture, which would close several remaining gaps at once.

At the end you will have a map: for each problem, the best known achievable ratio, the best known impossible ratio, and the gap between them. That gap is literally a list of open problems.

The knapsack FPTAS

Recall 0-1 knapsack: nn items with values vi∈Nv_i \in \N and weights wi∈Nw_i \in \N, capacity WW, and choose S⊆{1,…,n}S \subseteq \{1, \dots, n\} with ∑i∈Swi≤W\sum_{i \in S} w_i \le W maximizing ∑i∈Svi\sum_{i \in S} v_i. Assume without loss of generality each item fits alone, wi≤Ww_i \le W (discard non-fitting items first). This gives a free lower bound we soon use: OPT≥vmax⁡=max⁡ivi\mathrm{OPT} \ge v_{\max} = \max_i v_i.

Dynamic programming by value

Classical dynamic programming indexes capacity and costs O(nW)\bigO(nW). Another, symmetric version indexes value. Let V=∑iviV = \sum_i v_i and, for 0≤p≤V0 \le p \le V,

Ai(p)=min⁡{∑j∈Swj  :  S⊆{1,…,i}, ∑j∈Svj=p},A_i(p) = \min\Big\{\sum_{j \in S} w_j \;:\; S \subseteq \{1, \dots, i\},\ \sum_{j \in S} v_j = p\Big\},

the minimum weight with which the first ii items reach exactly value pp (+∞+\infty if unreachable). With A0(0)=0A_0(0) = 0 and A0(p)=∞A_0(p) = \infty for p>0p > 0, the recurrence is the familiar take-or-leave decision for item ii:

Ai(p)=min⁡(Ai−1(p), wi+Ai−1(p−vi)),A_i(p) = \min\big(A_{i-1}(p),\ w_i + A_{i-1}(p - v_i)\big),

where the second term counts only if vi≤pv_i \le p. The optimum is the largest pp with An(p)≤WA_n(p) \le W. The table has n(V+1)n(V + 1) cells, each filled in constant time: O(nV)⊆O(n2vmax⁡)\bigO(nV) \subseteq \bigO(n^2 v_{\max}). Like the other algorithm it is pseudopolynomial: polynomial in values, exponential in their number of bits. With six-digit values vmax⁡≈106v_{\max} \approx 10^6, the table already has on the order of n2⋅106n^2 \cdot 10^6 cells.

Scaling and rounding

Ibarra and Kim’s (1975) idea is that so much precision is unnecessary. If values had fewer significant digits, the table would be small. So remove digits: choose a unit KK, measure each value in integer multiples of KK, and solve the rounded problem exactly.

The new values are small integers: vi′≤vmax⁡/K=n/εv'_i \le v_{\max}/K = n/\eps, so V′=∑ivi′≤n2/εV' = \sum_i v'_i \le n^2/\eps and the table has O(n⋅n2/ε)=O(n3/ε)\bigO(n \cdot n^2/\eps) = \bigO(n^3/\eps) cells, with no trace of vmax⁡v_{\max}. How much is lost? Rounding loses less than one unit per item, vi−Kvi′<Kv_i - K v'_i < K. A set has at most nn items, so rounding changes any set’s value by less than nK=ε vmax⁡≤ε OPTnK = \eps\, v_{\max} \le \eps\,\mathrm{OPT}. That is the entire argument, and KK is chosen so this is exactly ε OPT\eps\,\mathrm{OPT}.

The formal proof is a chain of four inequalities, which you will reconstruct in the first guided exercise. What matters is where each hypothesis is used: optimality of SS for rounded values (not real ones), loss under KK per item, and vmax⁡≤OPTv_{\max} \le \mathrm{OPT}, where the assumption that every item fits alone enters.

InteractiveThe knapsack FPTAS
item value; lines every K (24 levels to the maximum)2w 323w 2323w 1217w 1813w 1511w 2412w 157w 4014w 1318w 368w 115w 10
  • chosen by FPTAS
  • lost in rounding
  • in the optimum
The number above each bar is the scaled value ⌊vi/K⌋\lfloor v_i / K \rfloor seen by dynamic programming. Each selected item loses less than KK (red), so total loss is below nK=ε vmax⁡≤ε OPTnK = \varepsilon\, v_{\max} \le \varepsilon\,\mathrm{OPT}. Here rounding removes 5.17% of the optimum from chosen items, versus 50.1% allowed by the bound: this is a worst case.
value / optimum versus 1/ε
  • FPTAS
  • guarantee 1 − ε
table cells (thousands) versus 1/ε
Instance
0.501
K=ε vmax⁡/nK = \varepsilon\, v_{\max} / n40 898
FPTAS value3 967 630
Optimum3 967 630
Ratio versus 1−ε1 - \varepsilon1.0000 ≥ 0.499
Table cells1608
Without scaling69.3 M
Each bar is an item: its height is real value and horizontal lines mark multiples of KK. Dynamic programming sees only the number of complete multiples (above the bar); red is discarded by rounding. Below, value/optimum ratio versus 1/ε1/\varepsilon, with dashed guarantee 1−ε1 - \varepsilon, and table size, growing linearly with 1/ε1/\varepsilon. Compare cells with the unscaled table’s requirement. Then choose the trap instance: it is designed for rounding to mislead dynamic programming.

On random instances the FPTAS almost always finds optimum even when ε\eps is enormous: the guarantee is worst-case, and the worst case requires rounding losses of many items to align against it. The trap instance aligns them deliberately. One large item of value vmax⁡v_{\max} is in every good solution; ten items are worth almost 2K2K each but round to 11; a decoy is worth slightly more than 10K10K, rounds to 1010 and weighs slightly less than the ten together. After rounding, “large plus decoy” ties “large plus ten” and weighs less, so dynamic programming chooses the decoy and loses almost 10K10K, close to the maximum nK=12KnK = 12K allowed by the analysis.

Approximation schemes: PTAS and FPTAS

The algorithm above is a family of algorithms, one per ε\eps, with an explicit accuracy/time tradeoff. The general definition distinguishes time dependence on ε\eps.

The difference is in the exponent. O(n3/ε)\bigO(n^3/\eps) is an FPTAS. O(n1/ε)\bigO(n^{1/\eps}) is a PTAS: for each ε\eps it is a polynomial, but of degree 1010 with ε=0.1\eps = 0.1 and degree 100100 with ε=0.01\eps = 0.01. In between is an EPTAS, time f(1/ε) poly(∣I∣)f(1/\eps)\,\mathrm{poly}(\abs{I}), where explosion in 1/ε1/\eps is not mixed with nn.

A PTAS with the exponent in view

Identical-machine scheduling, Pm∥Cmax⁡P_m \| C_{\max}, distributes nn jobs with durations p1≥p2≥⋯≥pnp_1 \ge p_2 \ge \cdots \ge p_n across mm machines to minimize the last completion time (makespan). List scheduling from the previous lesson (assign each job to the least-loaded machine) guarantees factor 2−1/m2 - 1/m. Graham (1969) observed that large jobs merely require careful treatment.

Proof

Let ℓ\ell be the last-finishing job and CC the makespan. If ℓ\ell is among the kk large jobs, its machine received no short job afterward (otherwise that would finish after ℓ\ell), so CC is one machine’s load in the optimal schedule of the kk large jobs, at most OPT\mathrm{OPT}. If ℓ\ell is short, when it was placed all machines had load at least its start time sℓs_\ell, so m sℓ≤∑j≠ℓpjm\,s_\ell \le \sum_{j \ne \ell} p_j and sℓ≤1m∑jpj≤OPTs_\ell \le \frac{1}{m}\sum_j p_j \le \mathrm{OPT}. Thus C=sℓ+pℓ≤OPT+pk+1C = s_\ell + p_\ell \le \mathrm{OPT} + p_{k+1}. Finally, the k+1k + 1 largest jobs are all at least pk+1p_{k+1} long and in any schedule some machine receives ⌈(k+1)/m⌉\lceil (k+1)/m\rceil of them: OPT≥k+1m pk+1\mathrm{OPT} \ge \frac{k+1}{m}\,p_{k+1}. Combining gives C≤OPT (1+mk+1)C \le \mathrm{OPT}\,(1 + \frac{m}{k+1}). With k=⌈m/ε⌉k = \lceil m/\eps\rceil, mk+1<ε\frac{m}{k+1} < \eps.

∎

For fixed mm this is an approximation scheme (indeed an EPTAS: 1/ε1/\eps appears only in constant m⌈m/ε⌉m^{\lceil m/\eps\rceil}, not in the exponent of nn), and also illustrates why a polynomial guarantee can be useless: with m=4m = 4 machines and ε=0.1\eps = 0.1, k=40k = 40 and 440≈1.2×10244^{40} \approx 1.2 \times 10^{24} assignments must be tried. If mm is part of the input, mm/εm^{m/\eps} ceases to be constant. For that case, Hochbaum and Shmoys (1987) gave a PTAS with 1/ε1/\eps in the exponent of nn, and later Alon, Azar, Woeginger and Yadid (1998) removed 1/ε1/\eps from the exponent with an EPTAS (Williamson and Shmoys chapter 3). Another famous PTAS is Arora’s (1998) for Euclidean planar traveling salesperson, in time n(log⁡n)O(1/ε)n(\log n)^{\bigO(1/\eps)}.

Why strongly NP-hard problems have no FPTAS

Could scheduling have an FPTAS? No, for a general reason. A problem is strongly NP-hard if it remains so when its numbers are polynomially bounded in input size, i.e. it does not even admit a pseudopolynomial algorithm (unless P = NP). Scheduling with mm part of the input is one (it contains 3-PARTITION), as is bin packing. Knapsack is not.

The idea: an FPTAS with ε<1/q\eps < 1/q makes an error smaller than 11 and, since values are integers, makes none. This gives an exact algorithm polynomial in ∣I∣\abs{I} and M(I)M(I), i.e. pseudopolynomial. You will prove it step by step in the exercises. Practical interpretation: if your problem is strongly NP-hard, a PTAS is the best one can hope for, and the exponent of 1/ε1/\eps is inevitably part of the price.

The primal-dual method

In the previous lesson you obtained factor ff for set cover by solving and rounding a linear program. It works, but the LP must be solved, expensive on large instances. The primal-dual method gets the same guarantee without solving anything: it simultaneously constructs an integer primal solution and a feasible dual solution certifying its quality, with cheap combinatorial operations.

Relaxed complementary slackness

Take a minimization LP and its dual, with A≥0\mat{A} \ge 0, b≥0\vb{b} \ge 0 and c≥0\vb{c} \ge 0:

(P)min⁡ c⊤x  s.a. Ax≥b, x≥0,(D)max⁡ b⊤y  s.a. A⊤y≤c, y≥0.\text{(P)}\quad \min\ \vb{c}\T\vb{x}\ \ \text{s.a.}\ \mat{A}\vb{x} \ge \vb{b},\ \vb{x} \ge \vb{0}, \qquad\qquad \text{(D)}\quad \max\ \vb{b}\T\vb{y}\ \ \text{s.a.}\ \mat{A}\T\vb{y} \le \vb{c},\ \vb{y} \ge \vb{0}.

By weak duality, every feasible y\vb{y} satisfies b⊤y≤OPTLP≤OPT\vb{b}\T\vb{y} \le \mathrm{OPT}_{LP} \le \mathrm{OPT}, where OPT\mathrm{OPT} is integer optimum. Complementary slackness conditions say a feasible pair is optimal if and only if xj>0⇒(A⊤y)j=cjx_j > 0 \Rightarrow (\mat{A}\T\vb{y})_j = c_j and yi>0⇒(Ax)i=biy_i > 0 \Rightarrow (\mat{A}\vb{x})_i = b_i. With integer x\vb{x} both cannot be required; the primal-dual method requires the first exactly and relaxes the second.

Proof

By condition 1, c⊤x=∑jcjxj=∑j(∑iaijyi)xj\vb{c}\T\vb{x} = \sum_j c_j x_j = \sum_j \big(\sum_i a_{ij} y_i\big) x_j, since jj with xj=0x_j = 0 contribute nothing to either side. Swapping sum order, ∑iyi(∑jaijxj)≤∑iyi β bi\sum_i y_i \big(\sum_j a_{ij} x_j\big) \le \sum_i y_i\, \beta\, b_i by condition 2 (ii with yi=0y_i = 0 contribute nothing). The final inequality is weak duality.

∎

This is the primal-dual approximation method: design a process growing y\vb{y} while keeping it feasible, adding to x\vb{x} only variables whose dual constraints are tight (condition 1), and stopping as soon as x\vb{x} is feasible. The approximation ratio is the β\beta for which condition 2 can be proved, and certificate b⊤y\vb{b}\T\vb{y} comes free: on each instance your solution is within factor c⊤x/b⊤y\vb{c}\T\vb{x}/\vb{b}\T\vb{y} of optimum, often much better than β\beta.

Set cover

In set cover there is a universe UU of nn elements and sets S1,…,Sm⊆US_1, \dots, S_m \subseteq U with costs cj≥0c_j \ge 0; frequency ff is the maximum number of sets containing one element. The LP and its dual are

min⁡∑jcjxj  s.a. ∑j: e∈Sjxj≥1  ∀e∈U,  x≥0;max⁡∑e∈Uye  s.a. ∑e∈Sjye≤cj  ∀j,  y≥0.\min \sum_j c_j x_j\ \ \text{s.a.}\ \sum_{j:\, e \in S_j} x_j \ge 1\ \ \forall e \in U,\ \ \vb{x} \ge \vb{0}; \qquad \max \sum_{e \in U} y_e\ \ \text{s.a.}\ \sum_{e \in S_j} y_e \le c_j\ \ \forall j,\ \ \vb{y} \ge \vb{0}.

The dual has an economic reading: each element ee pays yey_e to be covered, and no set can charge its elements more than it costs. The algorithm is a continuous process:

  1. Start with y=0\vb{y} = \vb{0} and no selected sets.
  2. Grow yey_e for all uncovered elements simultaneously at speed 1.
  3. When a set becomes tight, ∑e∈Sjye=cj\sum_{e \in S_j} y_e = c_j, add it to the solution: its elements become covered and their yey_e freeze.
  4. Repeat until everything is covered.

In practice continuous time is not simulated: at each stage compute each set’s remaining slack divided by its uncovered element count, then advance the minimum. There are at most mm stages, each in O(∑j∣Sj∣)\bigO(\sum_j \abs{S_j}).

Proof

y\vb{y} is always feasible: a set stops charging once tight because all its elements are covered and frozen. Every chosen set is tight (condition 1). For each element ∑j: e∈Sjxj≤f\sum_{j:\, e \in S_j} x_j \le f because only ff sets contain it (condition 2 with β=f\beta = f). The previous theorem gives the result.

∎
InteractiveDual growth in the primal-dual method
yₑ of each elementslack: paid / cost123456789S₁ · 32.00/3S₂ · 21.50/2S₃ · 42.00/4S₄ · 21.50/2S₅ · 32.00/3S₆ · 1.51.00/1.5S₇ · 2.51.50/2.5costdualOPT3·dual
  • uncovered element (its yey_e grows)
  • tight set: enters
  • covered element (frozen)
At time τ=0.50\tau = 0.50. Each set is paid by the sum of its elements’ yey_e; the first full bar enters next. No bar ever exceeds its cost: this is dual feasibility.
Instance
0.50
Dual ∑eye\sum_e y_e4.500
Primal cost0.00
f⋅f \cdot dual, with f=3f = 313.500
Integer optimum9.5
Chosen setsnone
Above, the dual variable yey_e for each element: those of uncovered elements (blue) rise together. In the middle, each row is a set and its dots are elements. On the right, each set’s slack bar: what elements pay against its cost. When a bar fills, the set is tight, turns orange, enters and freezes its elements. Below on a line: the dual, integer optimum, solution cost and ff times dual. Check that the dual never exceeds optimum and cost never exceeds ff times dual. In K3,3K_{3,3} with unit costs all vertices become tight simultaneously; activate reverse pruning.

In the initial figure instance (f=3f = 3), sets S2S_2 and S4S_4 become tight at τ=2/3\tau = 2/3, and S1S_1, S5S_5 and S6S_6 together at τ=5/6\tau = 5/6. Cost is 11.511.5, dual 6.56.5 and integer optimum 9.59.5: the certificate says the solution is within factor 11.5/6.5≈1.7711.5/6.5 \approx 1.77 of optimum, much better than the guaranteed 33. Also notice S6S_6 enters with S1S_1 and S5S_5, which already cover both its elements. Reverse pruning (visit chosen sets last to first and remove redundant ones) removes these redundancies: here cost drops to 1010. It does not improve the set-cover guarantee but is essential in other problems, as Steiner tree shows.

Vertex cover

Weighted vertex cover is set cover with edges as elements and each vertex as the set of its incident edges. Every edge belongs to exactly two sets: f=2f = 2, so primal-dual is a 2-approximation. In its simplest version, due to Bar-Yehuda and Even (1981), traverse edges in any order and, for each uncovered edge uvuv, increase yuvy_{uv} until uu or vv becomes tight. It is linear in graph size and solves no LP.

This analysis cannot improve factor 2, as graph K3,3K_{3,3} in the figure shows: with unit costs all nine edges rise to 1/31/3, all six vertices become tight simultaneously and the algorithm takes all of them, cost 6 versus optimum 3. The dual is 9⋅13=39 \cdot \tfrac{1}{3} = 3, equal to optimum: the problem is the primal solution, not the lower bound. Reverse pruning recovers optimum here but does not change the guaranteed factor 2. Nobody knowing how to guarantee 2−ε2 - \eps for any constant ε>0\eps > 0 is not a lack of imagination: if the unique games conjecture is true, it is impossible.

The Steiner tree idea

In Steiner tree a graph has costs ce≥0c_e \ge 0 and terminal set TT; connect terminals by a minimum-cost subgraph that may use nonterminals. The natural LP has one constraint per cut separating terminals: if δ(S)\delta(S) are edges leaving SS and SS contains some but not all terminals, then ∑e∈δ(S)xe≥1\sum_{e \in \delta(S)} x_e \ge 1. There are exponentially many, but primal-dual never writes them. Its dual has a variable ySy_S per cut, visualized as a moat around SS: an edge ee becomes tight when the sum of widths of crossed moats reaches cec_e.

The algorithm of Agrawal, Klein and Ravi (1995) and Goemans and Williamson (1995) grows moats simultaneously around connected components containing some but not all terminals. When an edge becomes tight, add it and merge two components. Once all terminals connect, reverse pruning removes unnecessary edges. Analysis shows active components have average degree at most 2 in the final tree at each instant, yielding factor 2. Without reverse pruning the argument fails because branches paid for by moats that do not need them would dangle. It is the same scheme just seen with a much richer dual (Williamson and Shmoys chapter 7).

Local search with guarantees

Local search is the algorithm everyone writes when unsure what to do: start with a solution, apply small improvements and stop at a local optimum, a solution improved by no allowed move. Surprisingly, sometimes every local optimum can be proved close to global optimum. The worst-case ratio between local and global optimum is the locality gap, and bounding it analyzes local search with approximation guarantees. To obtain an approximation algorithm one must also prove a local optimum (or something nearly as good) is reached in polynomial time.

MAX-CUT with single-vertex moves

MAX-CUT partitions vertices of graph G=(V,E)G = (V, E) with mm edges into two sides, maximizing edges with one endpoint on each side (the cut edges). The local move changes a vertex’s side. If d(v)d(v) is the degree of vv and c(v)c(v) its cut-edge count, moving it changes the cut by d(v)−2c(v)d(v) - 2c(v): uncut edges become cut and vice versa.

InteractiveLocal search for MAX-CUT
2/42/32/32/22/71/20/11/20/34/5
  • side 0
  • side 1
  • cut edge
  • moving improves the cut (ring)
Each vertex shows cut edges / degree. Ringed vertices have more uncut than cut edges, and moving them increases the cut by their gain d(v)−2 c(v)d(v) - 2\,c(v). Each move adds at least 1, so on an unweighted graph the search stops after at most m=16m = 16 moves.
Graph
Cut edges8
m/2m/28.0
Optimum (brute force)13
Largest gain+3
Moves0
Each vertex shows cut/degree, c(v)/d(v)c(v)/d(v), and its color shows its side. Cut edges are solid. Rings mark vertices improving the cut when moved (c(v)<d(v)/2c(v) < d(v)/2). Click a vertex to move it or let search move the greatest-gain vertex until a local optimum. Compare the cut with m/2m/2 and brute-force optimum. Try initial partitions: do you always reach the same cut? Then switch to K4,4K_{4,4}: the initial partition is already locally optimal.

The proof is a two-line counting argument you will do in the exercises; the figure puts it before you. The move count is immediate: each increases the cut by at least 1 and the cut is at most mm. Factor 1/21/2 is tight for this neighborhood: in K4,4K_{4,4}, putting two vertices from each bipartite side on each partition side leaves each vertex with 22 of its 44 edges cut, so moving nobody improves it, and the cut is 88 versus optimum 1616.

Weights change the story. Each move still improves, but possibly by tiny amounts, and graphs and starting points exist where local search takes exponentially many steps. Finding a local optimum of weighted MAX-CUT is in fact complete for PLS, the class of local-search problems (Schäffer and Yannakakis, 1991), so no polynomial method is expected. The standard remedy accepts only large improvements, increasing the cut by at least 2ε/n2\eps/n times its current value: the move count becomes polynomial in nn, 1/ε1/\eps and log⁡\log of total weight, at the cost of guarantee 1/(2+ε)1/(2 + \eps) instead of 1/21/2 (Kleinberg and Tardos, Algorithm Design, section 12.4).

k-median

In k-median, customers and possible centers lie in a metric space; open kk centers minimizing the sum of each customer’s distance to its closest center. The natural local move is a swap: close one open center and open a closed one. Arya, Garg, Khandekar, Meyerson, Munagala and Pandit (2004) proved the locality gap with single-center swaps is exactly 5, and allowing up to pp centers swapped at once lowers it to 3+2/p3 + 2/p, also tightly. For polynomial time, as with weighted MAX-CUT, accept only improvements exceeding a minimum relative factor, at the price of ε\eps in the factor. The proof sums carefully chosen inequalities, one per swap pairing local centers with optimum centers, and models most local-search analyses in clustering.

The lesson is methodological. Local search is the most-used practical heuristic, and these guarantees explain why it works: a local optimum is not merely “hard to improve with small changes”; its local-optimality inequalities, summed with appropriate weights, bound cost against global optimum.

Limits: gap reductions

So far, algorithms. How do we prove a factor cannot be achieved? An ordinary NP-completeness reduction is insufficient: it turns “yes” instances into ones with OPT≤c\mathrm{OPT} \le c and “no” into ones with OPT>c\mathrm{OPT} > c, and an approximate algorithm cannot distinguish cc from c+1c + 1. The reduction must open a gap.

Proof

Reduce from Hamiltonian cycle. Given G=(V,E)G = (V, E) with nn vertices, construct the complete graph with distance 11 on edges of EE and ρ(n) n+1\rho(n)\,n + 1 on the rest (the number has O(log⁡ρ(n)+log⁡n)\bigO(\log\rho(n) + \log n) bits, polynomial). If GG is Hamiltonian, a cycle of cost nn exists. Otherwise every cycle uses an edge absent from EE and costs at least (n−1)+ρ(n)n+1>ρ(n) n(n - 1) + \rho(n)n + 1 > \rho(n)\,n. A ρ(n)\rho(n)-approximation would return a cycle costing ≤ρ(n) n\le \rho(n)\,n exactly when GG is Hamiltonian.

∎

The proof essentially uses distances violating the triangle inequality. With it, metric traveling salesperson admits 3/23/2 (Christofides, 1976) and reduction-created gaps are small: the best known hardness is 123/122123/122 (Karpinski, Lampis and Schmied, 2015). The same technique, with distances 11 and 22, gives a tight result for k-center (open kk centers minimizing the maximum distance from a point to its center): a graph has a dominating set of size kk if and only if the metric “1 on edges, 2 otherwise” has a k-center of radius 1; otherwise radius 2. A factor-2−ε2 - \eps algorithm would distinguish the cases (Hsu and Nemhauser, 1979), and the previous lesson’s farthest-first greedy achieves exactly 2. Bin packing admits no factor below 3/23/2: deciding whether nn numbers fit into 2 bins of capacity 12∑iai\tfrac12\sum_i a_i is partition, so distinguishing 2 from 3 bins is already NP-hard.

These reductions create the gap by hand, exploiting special structure. For MAX-3SAT, MAX-CUT or vertex cover nothing so obvious exists: the Cook–Levin theorem reduction produces formulas which, if unsatisfiable, might have all but one clause satisfied. A much deeper idea is needed.

The PCP theorem

A proof that x∈Lx \in L, for L∈L \in NP, is a certificate checked by a verifier reading it all. What if it could read only a few bits? With an ordinary certificate that is impossible: a single wrong bit (one false clause) almost certainly escapes. PCP says every certificate can be rewritten redundantly, like an error-correcting code, so any false proof is wrong at a constant fraction of locations, and reading a constant number of random bits suffices to catch it.

This is the PCP theorem, the central complexity-theory result of the 1990s. Inclusion PCP[log⁡n,1]⊆NP\mathrm{PCP}[\log n, 1] \subseteq \mathrm{NP} is easy: with O(log⁡n)\bigO(\log n) random bits there are polynomially many random strings, a deterministic verifier can try them all, and the proof is queried at only polynomially many positions, forming the certificate. The other direction is hard: every NP proof admits a version checkable by reading a constant number of bits. The original proof combines algebraic codes (low-degree polynomials over finite fields) with verifier composition; Dinur (2007) found a combinatorial proof incrementally amplifying the gap with expander graphs.

The MAX-3SAT form

What makes PCP an approximation result is its equivalence to inapproximability. Call GAP-3SATρ\text{GAP-3SAT}_\rho the problem of distinguishing satisfiable 3CNF formulas from formulas where every assignment satisfies at most fraction ρ\rho of clauses (promising the input is one of the two types).

Proof

(2 ⇒ 1). Let L∈L \in be NP and gg the reduction from LL to GAP-3SATρ\text{GAP-3SAT}_\rho. Given xx, the verifier computes φ=g(x)\varphi = g(x) with mm clauses, interprets π\pi as an assignment to its variables, chooses a random clause (O(log⁡m)=O(log⁡n)\bigO(\log m) = \bigO(\log n) bits), reads its 3 variables and accepts if satisfied. If x∈Lx \in L, the satisfying assignment makes it always accept. Otherwise every assignment fails on at least fraction 1−ρ1 - \rho of clauses, so the verifier rejects with probability at least 1−ρ1 - \rho. Repeating t=⌈1/(1−ρ)⌉t = \lceil 1/(1 - \rho)\rceil times with independent clauses drops acceptance probability to ρt≤e−1<1/2\rho^t \le e^{-1} < 1/2, with 3t3t queries (a constant) and O(tlog⁡n)\bigO(t\log n) random bits.

(1 ⇒ 2). Let LL be NP-complete with a verifier using r=clog⁡nr = c\log n random bits and reading qq bits, with qq constant. For each random string R∈{0,1}rR \in \{0, 1\}^r, the qq queried positions i1,…,iqi_1, \dots, i_q and verifier decision are determined, so “VV accepts with string RR” is a Boolean function fRf_R of qq bits of π\pi. Write it as a CNF with at most 2q2^q clauses (one per rejected bit combination) and convert it to 3CNF using auxiliary variables as in the SAT to 3SAT reduction, with at most q 2qq\,2^q clauses. Formula φ\varphi is the conjunction over all RR: 2r⋅q2q=nc q2q2^r \cdot q2^q = n^c\,q2^q clauses, polynomially many. If x∈Lx \in L, the always-accepting proof (plus correct auxiliary values) satisfies φ\varphi. If x∉Lx \notin L, for every assignment (every π\pi), at least half of RR reject, and each leaves at least one clause in its group unsatisfied. The unsatisfied fraction is at least 122r/(2rq2q)=1/(q 2q+1)\tfrac{1}{2} 2^r / (2^r q2^q) = 1/(q\,2^{q+1}); choose ρ=1−1/(q 2q+1)\rho = 1 - 1/(q\,2^{q+1}).

∎

An (ρ+δ)(\rho + \delta)-approximation on a satisfiable formula would return an assignment with more than ρm\rho m clauses satisfied, impossible for the other instance type: it would decide GAP-3SATρ\text{GAP-3SAT}_\rho. Once MAX-3SAT has no PTAS, approximation-preserving reductions (Papadimitriou and Yannakakis’ L-reductions) propagate this to MAX-CUT, vertex cover, metric traveling salesperson, Steiner tree and all APX-hard problems: none has a PTAS unless P = NP.

Optimal thresholds

PCP gives a constant, but a tiny one. During the 1990s verifiers were refined until, for some problems, the hardness bound exactly matched the best algorithm. Three thresholds to know:

MAX-E3SAT: 7/8 (Håstad, 2001). If each clause has exactly three literals on distinct variables, a uniform random assignment leaves each clause unsatisfied with probability 1/81/8, so satisfies 7m/8≥78OPT7m/8 \ge \tfrac78\mathrm{OPT} clauses in expectation, and derandomization by conditional expectations makes this deterministic. Håstad proved doing better impossible: for every ε>0\eps > 0, distinguishing satisfiable formulas from those where at most fraction 7/8+ε7/8 + \eps of clauses is satisfiable is NP-hard. His verifier reads only 3 proof bits and accepts if their sum modulo 2 has a specified value. Astonishingly, the optimal algorithm is essentially the simplest possible: choose a random assignment without looking at the formula.

Set cover: ln n (Feige, 1998; Dinur and Steurer, 2014). Greedy guarantees Hn≤ln⁡n+1H_n \le \ln n + 1. Feige proved that, for every ε>0\eps > 0, no (1−ε)ln⁡n(1 - \eps)\ln n-approximation exists unless NP ⊆\subseteq DTIME(nO(log⁡log⁡n))(n^{\bigO(\log\log n)}), a somewhat stronger assumption than P ≠ NP. Dinur and Steurer weakened it to P ≠ NP: approximation below (1−ε)ln⁡n(1 - \eps)\ln n is NP-hard. Greedy is optimal up to lower-order terms.

k-center: 2. Just seen: an elementary gap reduction (Hsu and Nemhauser, 1979) against Gonzalez’s farthest-first greedy (1985). No PCP needed.

Semidefinite programs and the unique games conjecture

For MAX-CUT the random algorithm (each vertex on a side with probability 1/21/2) cuts m/2m/2 edges in expectation, like local search. For nearly twenty years nobody knew how to guarantee a constant above 1/21/2. Goemans and Williamson (1995) achieved it by going beyond linear programming.

The Goemans–Williamson algorithm

With weights wij≥0w_{ij} \ge 0 and xi∈{−1,+1}x_i \in \{-1, +1\} indicating sides, an edge is cut if xixj=−1x_i x_j = -1, so

MAXCUT=max⁡x∈{±1}n∑{i,j}∈Ewij 1−xixj2.\mathrm{MAXCUT} = \max_{\vb{x} \in \{\pm 1\}^n} \sum_{\{i,j\} \in E} w_{ij}\,\frac{1 - x_i x_j}{2}.

The relaxation replaces each number xix_i by a unit vector vi∈Rn\vb{v}_i \in \R^n and the product by the dot product:

SDP=max⁡∑{i,j}∈Ewij 1−vi⊤vj2s.a.∥vi∥2=1  ∀i.\mathrm{SDP} = \max \sum_{\{i,j\} \in E} w_{ij}\,\frac{1 - \vb{v}_i\T\vb{v}_j}{2} \quad\text{s.a.}\quad \norm{\vb{v}_i}_2 = 1\ \ \forall i.

This is a convex relaxation. A relaxation because vi=(xi,0,…,0)\vb{v}_i = (x_i, 0, \dots, 0) recovers any cut, so SDP≥OPT\mathrm{SDP} \ge \mathrm{OPT}. Convex, despite appearances: with Gram matrix X=[vi⊤vj]\mat{X} = [\vb{v}_i\T\vb{v}_j], the problem maximizes a linear function of X\mat{X} subject to X⪰0\mat{X} \succeq 0 and Xii=1X_{ii} = 1, a semidefinite program solvable to accuracy ε\eps in polynomial time. Vectors are recovered from X\mat{X} by Cholesky factorization. The rounding is randomized, but geometric: take a random hyperplane through the origin with normal r∼N(0,I)\vb{r} \sim \Normal(\vb{0}, \mat{I}), and place vertices according to which side their vectors fall on, xi=sign⁡(vi⊤r)x_i = \operatorname{sign}(\vb{v}_i\T\vb{r}).

Proof

Only the projection r′\vb{r}' of r\vb{r} onto the plane generated by vi\vb{v}_i and vj\vb{v}_j matters, because vi⊤r=vi⊤r′\vb{v}_i\T\vb{r} = \vb{v}_i\T\vb{r}'. The standard Gaussian is rotation-invariant, so r′\vb{r}' is a standard Gaussian in the plane and its direction is uniform on the circle. Signs of vi⊤r′\vb{v}_i\T\vb{r}' and vj⊤r′\vb{v}_j\T\vb{r}' differ exactly when the direction of r′\vb{r}' lies in one of the two opposite arcs between perpendiculars to vi\vb{v}_i and vj\vb{v}_j, each of length θij\theta_{ij}. The probability is 2θij/2π2\theta_{ij}/2\pi. (The probability that r′\vb{r}' is zero or perpendicular to either is zero.)

∎
InteractiveThe random hyperplane
rvᵢvⱼ
cut probability versus SDP contribution
  • θ/π
  • (1 − cos θ)/2
ratio between the two
  • ratio
  • α (minimum)
  • separating normals r\vb{r} (two arcs of length θ\theta)
  • positive side of hyperplane
  • negative side
With θ=100°\theta = 100° the hyperplane cuts the edge with probability θ/π=0.556\theta/\pi = 0.556, and the SDP counts it as (1−cos⁡θ)/2=0.587(1 - \cos\theta)/2 = 0.587. The ratio is 0.947: find the angle minimizing the ratio.
100°
P[separate]=θ/π\Pr[\text{separate}] = \theta/\pi0.5556
Observed frequency0.530 (200)
SDP contribution (1−cos⁡θ)/2(1-\cos\theta)/20.5868
Ratio0.9467
Left: two vectors in their plane and normals r\vb{r} of sampled hyperplanes; those separating vectors lie in the two magenta arcs, each length θ\theta. Sample several hundred and compare observed frequency with θ/π\theta/\pi. Right: probability of cutting the edge, θ/π\theta/\pi, against its SDP contribution (1−cos⁡θ)/2(1 - \cos\theta)/2 and their ratio. Sweep θ\theta: where is the worst angle? Why does the ratio shoot up for small angles?
Proof

By linearity of expectation and the previous theorem, E[corte]=∑wij θij/π\E[\text{corte}] = \sum w_{ij}\,\theta_{ij}/\pi. By definition of αGW\alpha_{GW}, θ/π≥αGW(1−cos⁡θ)/2\theta/\pi \ge \alpha_{GW}(1 - \cos\theta)/2 for every θ∈(0,π]\theta \in (0, \pi] and also θ=0\theta = 0, where both sides are zero. With cos⁡θij=vi⊤vj\cos\theta_{ij} = \vb{v}_i\T\vb{v}_j and wij≥0w_{ij} \ge 0, summing gives E[corte]≥αGW∑wij(1−vi⊤vj)/2=αGW⋅SDP\E[\text{corte}] \ge \alpha_{GW} \sum w_{ij}(1 - \vb{v}_i\T\vb{v}_j)/2 = \alpha_{GW}\cdot\mathrm{SDP}.

∎

You will compute the numerical value of αGW\alpha_{GW} and its minimizing angle in the exercises. Three qualifications. The SDP is solved to arbitrarily small additive error, so the actual guarantee is αGW−ε\alpha_{GW} - \eps; repeated rounding gives high probability, and derandomization exists (Mahajan and Ramesh, 1999). Assumption wij≥0w_{ij} \ge 0 is essential: negative weights break the summation argument. The analysis cannot be improved by comparing with the SDP: this relaxation’s integrality gap, the infimum of OPT/SDP\mathrm{OPT}/\mathrm{SDP} over graphs, is exactly αGW\alpha_{GW} (Feige and Schechtman, 2002). A 5-cycle already gives a close ratio, as an exercise shows.

The unique games conjecture

The MAX-CUT gap is huge: αGW≈0.878\alpha_{GW} \approx 0.878 with SDP, and best NP hardness 16/17≈0.94116/17 \approx 0.941 (Håstad, 2001, with a gadget by Trevisan, Sorkin, Sudan and Williamson, 2000). Vertex cover is similar: 2 by primal-dual versus 2\sqrt 2 known NP-hard (Khot, Minzer and Safra, 2018; previously 1.361.36 by Dinur and Safra, 2005). Khot (2002) proposed a conjecture closing both at once.

“Unique” means one endpoint’s label determines the other’s. Thus the conjecture concerns 1−ε1 - \eps and not 11: if all constraints can be satisfied, fix one vertex label per component (trying the kk possibilities) and propagate it in polynomial time. A concrete example is systems of equations xu−xv≡cuv(modk)x_u - x_v \equiv c_{uv} \pmod k: solving them is easy; satisfying almost all when not all can be satisfied is what the conjecture says is hard.

If UGC is true:

  • MAX-CUT: exceeding αGW+ε\alpha_{GW} + \eps is NP-hard (Khot, Kindler, Mossel and O’Donnell, 2007, using Mossel, O’Donnell and Oleszkiewicz’s “majority is stablest” theorem). Goemans–Williamson would be optimal, and constant 0.8780.878 would cease to be an analysis artifact and become a constant of nature.
  • Vertex cover: 2−ε2 - \eps is NP-hard (Khot and Regev, 2008). The primal-dual method just seen would be optimal.
  • All CSPs: Raghavendra (2008) proved that for every constraint satisfaction problem a canonical semidefinite program with appropriate rounding reaches the best possible factor under UGC. Semidefinite programs would be the universal approximation algorithm.

The conjecture remains open. Evidence points both ways: Arora, Barak and Steurer (2010) gave a subexponential algorithm for unique games, so if the exponential-time hypothesis holds, no reduction from 3SAT can produce linear-size unique games (UGC, if true, requires reductions with large polynomial blowup). Khot, Minzer and Safra (2018) proved the 2-to-2 games conjecture, a weaker variant, implying in particular that distinguishing unique games of value near 1/21/2 from near-zero value is NP-hard. From that proof comes 2\sqrt 2 for vertex cover.

The approximability map

Put everything on an axis. On the left, problems with approximation schemes; then those admitting a constant factor but no PTAS (class APX, home to APX-hard problems); then logarithmic-factor problems, then polynomial-factor, and on the right those admitting no factor.

InteractiveThe approximability landscape
1+ε∞constant (APX)ln nnKnapsack (max.)Scheduling P||CmaxEuclidean TSPMetric TSPSteiner treeMAX-E3SAT (max.)MAX-CUT (max.)Vertex coverk-centerSet coverMaximum clique (max.)General TSP1.011.051.252162¹⁶
  • best known algorithm
  • hardness bound (P ≠ NP)
  • hardness bound under UGC
  • open gap
Vertex cover. Algorithm: 2 by primal–dual, LP rounding or a maximal matching. Hardness: 2−ε\sqrt 2 - \varepsilon is NP-hard (Khot, Minzer and Safra, 2018); previously 1.361.36 (Dinur and Safra, 2005). Enable UGC: Under UGC, 2−ε2 - \varepsilon is NP-hard (Khot and Regev, 2008): factor 2 is optimal.
Axis on a log⁡log⁡\log\log factor scale, with n=106.0n = 10^{6.0} (1.00 M).
10^6.0
Closed gaps (P ≠ NP only)5 of 12
Closed gaps with UGC7 of 12
Greedy cover, ln⁡n+1\ln n + 114.82
Vertex cover: algorithm2.000
Hardness1.414
Each row is a problem. The blue dot is the best known algorithm and the red bar the best hardness bound under P ≠ NP (or the stated assumption): below it approximation is NP-hard. The gap is unknown. Maximization plots OPT/ALG, so 0.878 appears as 1.138. The axis is doubly logarithmic to fit both 1.01 and nn. Click a row to see where numbers come from, move nn (which rows shift?) and activate the unique games conjecture: which gaps close?

Three lessons from the map. First, few gaps are closed: knapsack (FPTAS), scheduling (PTAS, no FPTAS possible), MAX-E3SAT, k-center and general traveling salesperson; set cover and clique only up to lower-order terms. Euclidean traveling salesperson with its PTAS appears unclosed: no FPTAS is known and this lesson’s strong-hardness theorem does not rule it out directly, because tour lengths are sums of square roots, not integers. Second, gaps for metric traveling salesperson and Steiner tree are enormous (1.0081.008 versus 1.51.5, 1.011.01 versus 1.391.39): known hardness techniques barely touch them. Third, UGC is no detail: it decides whether two of the most studied theoretical problems are solved.

Reading an approximation hardness result

A statement like “for every ε>0\eps > 0, approximating Π\Pi within factor ρ−ε\rho - \eps is NP-hard” has four parts to check:

  1. Assumption. P ≠ NP, NP ⊈\not\subseteq DTIME(nO(log⁡log⁡n))(n^{\bigO(\log\log n)}), NP ≠ ZPP, UGC and the exponential-time hypothesis differ. A “under UGC” result may fall if the conjecture does.
  2. Instance class. Metric, Euclidean and general traveling salesperson have completely different answers. Hardness applies to the class produced by the reduction, and a subclass (planar graphs, bounded degree, small treewidth) may be much easier.
  3. Guarantee type. Worst-case, multiplicative factor, every instance. It says nothing about average case, structured instances, or additive or asymptotic guarantees: bin packing admits no factor below 3/23/2, but does admit (1+ε)OPT+1(1 + \eps)\mathrm{OPT} + 1 (Fernandez de la Vega and Lueker, 1981).
  4. Quantifiers. “For every ε\eps” versus “for some ε\eps”, and whether ρ\rho depends on nn.

First, the FPTAS from scratch, with value-indexed dynamic programming and reconstruction, compared with exact optimum (computed by capacity DP, which is small here) over 40 random instances per ε\eps, with six-digit values.

[ ]The knapsack FPTASBrowser
import numpy as np

def mochila_exacta(v, w, W):
    """Óptimo exacto por programación dinámica sobre la capacidad: O(n W)."""
    best = np.zeros(W + 1, dtype=np.int64)
    for vi, wi in zip(v, w):
        if wi <= W:
            best[wi:] = np.maximum(best[wi:], best[:W + 1 - wi] + vi)
    return int(best[W])

def mochila_por_valor(v, w, W):
    """A[p] = peso mínimo para conseguir valor exactamente p. Devuelve (conjunto, celdas)."""
    n, P = len(v), int(sum(v))
    A = np.full(P + 1, np.inf)
    A[0] = 0.0
    toma = np.zeros((n, P + 1), dtype=bool)
    for i in range(n):
        if v[i] == 0:
            continue
        cand = np.full(P + 1, np.inf)
        cand[v[i]:] = A[:P + 1 - v[i]] + w[i]
        mejor = cand < A
        toma[i] = mejor
        A = np.where(mejor, cand, A)
    p = int(np.max(np.nonzero(A <= W)[0]))       # mayor valor alcanzable sin pasarse
    S = []
    for i in range(n - 1, -1, -1):                # reconstrucción hacia atrás
        if toma[i, p]:
            S.append(i)
            p -= v[i]
    return S[::-1], n * (P + 1)

def fptas_mochila(v, w, W, eps):
    v = np.asarray(v)
    n = len(v)
    K = eps * v.max() / n
    v_esc = np.floor(v / K).astype(np.int64)
    S, celdas = mochila_por_valor(v_esc, w, W)
    return int(v[S].sum()), celdas

rng = np.random.default_rng(0)
n = 20
print(" eps   peor valor/OPT   media     1-eps   celdas (media)   sin escalar (media)")
for eps in [0.5, 0.2, 0.1, 0.05, 0.02]:
    peor, suma, celdas, crudas = 1.0, 0.0, [], []
    for _ in range(40):
        v = rng.integers(10**5, 10**6, n)
        w = rng.integers(5, 60, n)
        W = int(0.4 * w.sum())
        opt = mochila_exacta(v, w, W)
        val, c = fptas_mochila(v, w, W, eps)
        assert val >= (1 - eps) * opt             # la garantía del teorema
        peor, suma = min(peor, val / opt), suma + val / opt
        celdas.append(c)
        crudas.append(n * (int(v.sum()) + 1))
    print(f"{eps:5.2f}   {peor:.5f}          {suma / 40:.5f}   {1 - eps:.2f}    {np.mean(celdas):>12,.0f}   {np.mean(crudas):>16,.0f}")
print(f"cota n^3/eps con eps = 0.02: {n**3 / 0.02:,.0f} celdas")

All 200 runs meet the guarantee, with enormous slack: worst ratio at ε=0.5\eps = 0.5 is 0.998170.99817, far from promised 0.50.5, and at ε=0.02\eps = 0.02 the worst ratio already rounds to 1.000001.00000. Table size grows as theory predicts: from about 9 0009\,000 cells at ε=0.5\eps = 0.5 to about 231 000231\,000 at ε=0.02\eps = 0.02, factor 25.525.5 for ratio 2525 in 1/ε1/\eps, below bound n3/ε=400 000n^3/\eps = 400\,000. Unscaled, the same DP would need about 2.2×1082.2 \times 10^8 cells. The gap between guarantee and observation is the same seen in the figure: rounding losses do not align on random instances.

Now primal-dual set cover on instances where each element is in exactly ff sets. Compare cost with its constructed dual, integer optimum (scipy.optimize.milp) and LP optimum (linprog).

[ ]Primal-dual set coverBrowser
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds

def primal_dual_cobertura(conjuntos, costes, n_elem):
    """Crecimiento dual uniforme. Devuelve (elegidos en orden de entrada, y)."""
    m = len(conjuntos)
    y = np.zeros(n_elem)
    pagado = np.zeros(m)
    cubierto = np.zeros(n_elem, dtype=bool)
    elegidos = []
    while not cubierto.all():
        activos = np.array([sum(not cubierto[e] for e in S) for S in conjuntos])
        tiempo = np.array([(costes[j] - pagado[j]) / activos[j] if activos[j] > 0 and j not in elegidos else np.inf
                           for j in range(m)])
        dt = tiempo.min()                          # el próximo conjunto en ajustarse
        y[~cubierto] += dt
        pagado += dt * activos
        for j in np.nonzero(tiempo <= dt + 1e-12)[0]:
            elegidos.append(int(j))
            for e in conjuntos[j]:
                cubierto[e] = True
    return elegidos, y

def poda_inversa(elegidos, conjuntos, n_elem):
    sol = list(elegidos)
    for j in reversed(elegidos):
        resto = [k for k in sol if k != j]
        if len(set().union(*[conjuntos[k] for k in resto])) == n_elem:
            sol = resto
    return sol

def instancia(rng, n_elem, m, f):
    """Cada elemento está en exactamente f conjuntos al azar: frecuencia f."""
    conjuntos = [set() for _ in range(m)]
    for e in range(n_elem):
        for j in rng.choice(m, f, replace=False):
            conjuntos[j].add(e)
    return conjuntos, rng.uniform(1, 10, m).round(1)

def optimos(conjuntos, costes, n_elem):
    M = np.zeros((n_elem, len(conjuntos)))
    for j, S in enumerate(conjuntos):
        M[list(S), j] = 1
    lp = linprog(costes, A_ub=-M, b_ub=-np.ones(n_elem), bounds=(0, 1), method="highs").fun
    ip = milp(costes, constraints=LinearConstraint(M, lb=1), integrality=np.ones(len(costes)), bounds=Bounds(0, 1)).fun
    return lp, ip

rng = np.random.default_rng(1)
print(" f   coste/dual (máx)   coste/OPT (máx)   con poda/OPT (máx)   OPT/LP (máx)")
for f in [2, 3, 5]:
    r_dual = r_opt = r_poda = r_gap = 0.0
    for _ in range(20):
        C, c = instancia(rng, 30, 20, f)
        sel, y = primal_dual_cobertura(C, c, 30)
        coste = c[sel].sum()
        poda = c[poda_inversa(sel, C, 30)].sum()
        lp, ip = optimos(C, c, 30)
        assert y.sum() <= lp + 1e-6 and coste <= f * y.sum() + 1e-6   # dual <= LP y coste <= f dual
        r_dual, r_opt = max(r_dual, coste / y.sum()), max(r_opt, coste / ip)
        r_poda, r_gap = max(r_poda, poda / ip), max(r_gap, ip / lp)
    print(f"{f:2d}   {r_dual:.3f} (<= {f})        {r_opt:.3f}             {r_poda:.3f}                {r_gap:.3f}")

Three observations in the table. Cost/dual, the algorithm’s own certificate, always stays below ff, substantially: at most 1.491.49, 1.711.71 and 2.082.08 for f=2,3,5f = 2, 3, 5. The true ratio against optimum is smaller still (1.241.24, 1.341.34 and 1.551.55 worst case), because the dual is below optimum for two additive reasons: slack between the constructed dual and LP optimum, and the LP-to-integer integrality gap, reaching 1.071.07, 1.171.17 and 1.201.20 here. Reverse pruning helps more as ff grows because more overlap adds redundant sets: worst ratio drops from 1.241.24 to 1.111.11 at f=2f = 2 and from 1.551.55 to 1.241.24 at f=5f = 5.

Finally local search for MAX-CUT, from 10 random partitions on each of 20 random graphs G(14,0.3)G(14, 0.3), versus exact brute-force maximum (vectorized over 2132^{13} cuts fixing vertex 0), and the worst case of K4,4K_{4,4}.

[ ]Local search for MAX-CUTBrowser
import numpy as np

def corte(x, aristas):
    return int(np.sum(x[aristas[:, 0]] != x[aristas[:, 1]]))

def busqueda_local(x, n, aristas):
    """Mueve un vértice mientras eso aumente el corte. Devuelve (x, número de movimientos)."""
    x = x.copy()
    vecinos = [[] for _ in range(n)]
    for a, b in aristas:
        vecinos[a].append(b); vecinos[b].append(a)
    pasos, mejora = 0, True
    while mejora:
        mejora = False
        for u in range(n):
            iguales = sum(x[w] == x[u] for w in vecinos[u])
            if iguales > len(vecinos[u]) - iguales:     # ganancia d(u) - 2 c(u) > 0
                x[u] ^= 1
                pasos, mejora = pasos + 1, True
    return x, pasos

def max_corte_exacto(n, aristas):
    """Fuerza bruta vectorizada: el vértice 0 fijo en el lado 0, 2^(n-1) cortes."""
    X = (np.arange(2 ** (n - 1))[:, None] >> np.arange(n - 1)) & 1
    X = np.hstack([np.zeros((len(X), 1), dtype=X.dtype), X])
    return int((X[:, aristas[:, 0]] != X[:, aristas[:, 1]]).sum(axis=1).max())

rng = np.random.default_rng(2)
n, p = 14, 0.3
peor, peor_m2, max_pasos, max_m = np.inf, np.inf, 0, 0
for g in range(20):
    aristas = np.array([(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < p])
    m = len(aristas)
    opt = max_corte_exacto(n, aristas)
    for _ in range(10):
        x, pasos = busqueda_local(rng.integers(0, 2, n), n, aristas)
        c = corte(x, aristas)
        assert 2 * c >= m                                # el teorema
        peor, peor_m2 = min(peor, c / opt), min(peor_m2, c / (m / 2))
        max_pasos, max_m = max(max_pasos, pasos), max(max_m, m)
print(f"200 óptimos locales en 20 grafos G({n}, {p}), con hasta {max_m} aristas:")
print(f"  peor corte/OPT = {peor:.3f}   peor corte/(m/2) = {peor_m2:.3f}   máximo de movimientos = {max_pasos}")

# el peor caso: K_{4,4} con cada lado del bipartito partido por la mitad
k44 = np.array([(a, b) for a in range(4) for b in range(4, 8)])
x = np.array([0, 0, 1, 1, 0, 0, 1, 1])
_, pasos = busqueda_local(x, 8, k44)
print(f"K4,4: corte {corte(x, k44)}, movimientos {pasos}, OPT {max_corte_exacto(8, k44)}, m/2 = {len(k44) // 2}")

No local optimum falls below m/2m/2, as the theorem guarantees, but on these graphs none approaches it: worst cuts 1.241.24 times m/2m/2, and worst ratio against exact optimum is 0.7830.783, far from the theorem’s 1/21/2. At most 9 moves are needed on graphs with up to 38 edges: the mm-move bound is pessimistic. And K4,4K_{4,4} shows 1/21/2 is tight: the initial partition is already locally optimal, 0 moves, cut 8=m/28 = m/2 and optimum 1616.

Solving the SDP requires a semidefinite solver. None exists in the browser, so solve from scratch with Burer and Monteiro’s idea: optimize directly over vectors vi∈Rr\vb{v}_i \in \R^r with small rr. MAX-CUT has a simple coordinate update. Fixing other vectors, the objective depends on vi\vb{v}_i through −12vi⊤∑jwijvj-\tfrac12\vb{v}_i\T\sum_j w_{ij}\vb{v}_j, maximized over the unit sphere at vi=−g/∥g∥2\vb{v}_i = -\vb{g}/\norm{\vb{g}}_2 with g=∑jwijvj\vb{g} = \sum_j w_{ij}\vb{v}_j. This “mixing method” (Wang, Chang and Kolter, 2017) alone does not guarantee global optimum, but trust is unnecessary: SDP weak duality produces a certified upper bound, and since the SDP is strictly feasible (X=I\mat{X} = \mat{I} is positive definite), strong duality holds and this bound can be exact. The dual of max⁡14⟨L,X⟩\max \tfrac14\langle\mat{L}, \mat{X}\rangle with Xii=1X_{ii} = 1 and X⪰0\mat{X} \succeq 0, where L\mat{L} is the weighted Laplacian, is min⁡∑iyi\min \sum_i y_i subject to diag⁡(y)−14L⪰0\diag(\vb{y}) - \tfrac14\mat{L} \succeq 0. Any feasible y\vb{y} upper-bounds the SDP because 14⟨L,X⟩≤⟨diag⁡(y),X⟩=∑iyi\tfrac14\langle\mat{L}, \mat{X}\rangle \le \langle\diag(\vb{y}), \mat{X}\rangle = \sum_i y_i. Take y\vb{y} suggested by complementary slackness, yi=14(LX)iiy_i = \tfrac14(\mat{L}\mat{X})_{ii}, and if diag⁡(y)−14L\diag(\vb{y}) - \tfrac14\mat{L} has a negative eigenvalue λ\lambda, subtract λ\lambda from every yiy_i to make it feasible.

[ ]Goemans–Williamson from scratchBrowser
import numpy as np

def grafo(n, p, semilla):
    r = np.random.default_rng(semilla)
    Wm = np.triu((r.random((n, n)) < p).astype(float), 1)
    return Wm + Wm.T

def sdp_maxcut_bm(Wm, r=None, iters=300, semilla=0):
    """Burer-Monteiro por coordenadas (método de mezcla): v_i = -normaliza(sum_j w_ij v_j)."""
    n = len(Wm)
    r = r or int(np.ceil(np.sqrt(2 * n))) + 1
    V = np.random.default_rng(semilla).normal(size=(n, r))
    V /= np.linalg.norm(V, axis=1, keepdims=True)
    for _ in range(iters):
        for i in range(n):
            g = Wm[i] @ V
            ng = np.linalg.norm(g)
            if ng > 0:
                V[i] = -g / ng
    return V

def cota_superior(Wm, V):
    """Dual factible: y con diag(y) - L/4 semidefinida; su suma acota la SDP por arriba."""
    L = np.diag(Wm.sum(1)) - Wm
    y = np.einsum("ij,ji->i", L, V @ V.T) / 4       # holgura complementaria: y_i = (L X)_ii / 4
    lam = np.linalg.eigvalsh(np.diag(y) - L / 4)[0]
    return y.sum() - len(y) * min(lam, 0.0)

def corte_w(Wm, x):
    return int((Wm * (x[:, None] != x[None, :])).sum() / 2)

Wm = grafo(60, 0.1, 3)
m = int(Wm.sum() / 2)
V = sdp_maxcut_bm(Wm)
L = np.diag(Wm.sum(1)) - Wm
sdp_inf, sdp_sup = np.trace(L @ V @ V.T) / 4, cota_superior(Wm, V)
print(f"n = 60, m = {m}:   SDP en [{sdp_inf:.4f}, {sdp_sup:.4f}]")

rng = np.random.default_rng(4)
cortes = [corte_w(Wm, (V @ rng.normal(size=V.shape[1]) >= 0).astype(int)) for _ in range(200)]
aristas = np.argwhere(np.triu(Wm) > 0)
locales = [corte(busqueda_local(rng.integers(0, 2, 60), 60, aristas)[0], aristas) for _ in range(30)]
print(f"hiperplano, 200 lanzamientos:   media {np.mean(cortes):.1f}   mejor {max(cortes)}   media/SDP {np.mean(cortes) / sdp_sup:.3f}")
print(f"búsqueda local, 30 arranques:   media {np.mean(locales):.1f}   mejor {max(locales)}")
print(f"garantía alpha_GW * SDP = {0.87856 * sdp_sup:.1f}   m/2 = {m / 2}")

The lower bound (computed vector value) and upper bound (dual certificate) agree in 156.2180156.2180 to four decimal places, so mixing found the SDP optimum: no cut in this graph exceeds 156156 edges. The random hyperplane cuts 140.8140.8 on average, 0.9020.902 of SDP, above guarantee 137.2137.2; the best of 200 samples cuts 147. Local search from 30 random partitions is slightly lower on average (138.6138.6) and its best result, 146, is nearly the same.

Local search competing well on a random graph contradicts nothing: 1/21/2 is worst-case and local optima on random graphs are often good. The difference is what each method knows about itself. Local search offers no better upper bound than m=194m = 194; the SDP certifies nothing exceeds 156.2156.2, so the best cut found, 147, is within 6 %6\,\% of optimum. In the worst case the hyperplane guarantees 0.8780.878 where local search guarantees only 1/21/2, as in K4,4K_{4,4}, where SDP assigns opposite vectors to the two sides and the hyperplane finds the perfect cut.

With a modeler like CVXPY the SDP is written directly over matrix X\mat{X}. CVXPY is unavailable in the browser, so this cell runs in the local lab; it uses the same graph (same seed) for comparison with mixing.

[ ]The SDP with CVXPYLocal GPU
import numpy as np
import cvxpy as cp

r = np.random.default_rng(3)
Wm = np.triu((r.random((60, 60)) < 0.1).astype(float), 1)
Wm = Wm + Wm.T
L = np.diag(Wm.sum(1)) - Wm

X = cp.Variable((60, 60), symmetric=True)
problema = cp.Problem(cp.Maximize(cp.trace(L @ X) / 4), [X >> 0, cp.diag(X) == 1])
problema.solve(solver=cp.CLARABEL)
print(f"estado: {problema.status}   valor de la SDP: {problema.value:.4f}")

# vectores por factorización espectral (Cholesky falla si X es singular, que es lo normal)
w, U = np.linalg.eigh(X.value)
V = U * np.sqrt(np.clip(w, 0, None))
print("rango numérico de X:", int((w > 1e-6 * w.max()).sum()))
rng = np.random.default_rng(4)
cortes = []
for _ in range(200):
    x = V @ rng.normal(size=V.shape[1]) >= 0
    cortes.append(int((Wm * (x[:, None] != x[None, :])).sum() / 2))
print(f"hiperplano sobre la solución de CVXPY: media {np.mean(cortes):.1f}   mejor {max(cortes)}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

CVXPY (with Clarabel solver) gives the same value 156.2180156.2180, confirming the previous cell’s certificate. The hyperplane on its solution cuts 141.6141.6 on average and at most 149, slightly more than on Burer–Monteiro’s: both have the same value but differ as matrices, and rounding depends on vectors, not just SDP value. Guarantee αGW\alpha_{GW} applies to any optimal solution; which rounds better on a particular instance is empirical.

Typical mistakes

Exercises

ProofThe FPTAS ratio
Prove: The knapsack FPTAS returns a set SS with v(S)≥(1−ε) OPTv(S) \ge (1 - \varepsilon)\,\mathrm{OPT} in time O(n3/ε)O(n^3/\varepsilon), where v(S)=∑i∈Sviv(S) = \sum_{i \in S} v_i.
0
Let OO be an optimal set, K=εvmax⁡/nK = \varepsilon v_{\max}/n and vi′=⌊vi/K⌋v'_i = \lfloor v_i/K \rfloor. Every item fits alone in the knapsack.

Step 1 of 5. What is the first useful inequality?

NumericThe FPTAS by hand
Four items with values (1010,620,620,380)(1010, 620, 620, 380) and weights (6,4,4,3)(6, 4, 4, 3), capacity W=8W = 8. Apply the FPTAS with ε=0.5\varepsilon = 0.5. Dynamic programming stores, for each scaled value, the minimum weight attaining it, and returns the set with highest scaled value at weight at most WW. What real value does the returned set have?
QuizWhich are FPTAS?
Each bound is the running time of a scheme guaranteeing factor 1+ε1 + \varepsilon for every ε∈(0,1]\varepsilon \in (0, 1], with nn input size. Which are FPTAS?

More than one answer may be correct.

ProofStrong hardness rules out an FPTAS
Prove: Let Π\Pi be a minimization problem with integer objective values and polynomial qq such that OPT(I)<q(∣I∣,M(I))\mathrm{OPT}(I) < q(\abs{I}, M(I)), where M(I)M(I) is the largest number in II. If Π\Pi is strongly NP-hard and P ≠ NP, Π\Pi has no FPTAS.
0
Suppose Π\Pi has an FPTAS A\mathcal{A}, polynomial-time in ∣I∣\abs{I} and 1/ε1/\varepsilon.

Step 1 of 4. What ε\varepsilon do you choose for each instance II?

CodePrimal-dual vertex cover
Implement vc_primal_dual(n, aristas, coste) (vertices 0..n-1, aristas a list of pairs, coste a list of positive numbers) with the Bar-Yehuda–Even algorithm: traverse edges in order and, for each edge uvuv with neither endpoint in the cover, increase yuvy_{uv} as far as possible, until uu or vv becomes tight (∑e∋uye=cu\sum_{e \ni u} y_e = c_u), and add tight endpoints to the cover. Return (cubierta, y): a set of vertices and dictionary {(u, v): y_uv} with one entry per edge. Tests check that the cover is valid, y is feasible, every chosen vertex is tight, and the cost certificate ≤2∑ye\le 2\sum y_e.
def vc_primal_dual(n, aristas, coste):
  """Devuelve (cubierta, y): un recubrimiento por vértices y un dual factible."""
  cubierta = set(range(n))            # tu código: esto es válido pero no está certificado
  y = {e: 0.0 for e in aristas}
  return cubierta, y
Shift+Enter to run
ProofLocal optima cut half
Prove: If (A,B)(A, B) is a MAX-CUT local optimum under moving one vertex to the other side, it cuts at least m/2m/2 edges.
0
For each vertex vv, let d(v)d(v) be its degree and c(v)c(v) its incident cut-edge count.

Step 1 of 3. What does local optimality say at vertex vv?

QuizTwo faces of the PCP theorem
Which statement is correct?
NumericThe gap produced by a verifier
A verifier for an NP-complete language uses O(log⁡n)O(\log n) random bits, reads exactly 3 proof bits and has soundness 1/21/2. With the lesson construction, each random string gives at most 23=82^3 = 8 3-literal clauses (no auxiliary variables needed). If x∉Lx \notin L, what maximum fraction ρ\rho of formula clauses can be satisfied according to the argument?
NumericThe worst Goemans–Williamson angle
Numerically minimize g(θ)=2π θ1−cos⁡θg(\theta) = \dfrac{2}{\pi}\,\dfrac{\theta}{1 - \cos\theta} on (0,π](0, \pi]. At what angle θ⋆\theta^\star, in degrees to at least one decimal place, is the minimum αGW\alpha_{GW} attained?
NumericThe pentagon integrality gap
In the unweighted 5-vertex cycle C5C_5 the maximum cut is 4. The Goemans–Williamson SDP reaches optimum by placing vectors in a plane, each rotated 4π/54\pi/5 relative to its predecessor along the cycle. Compute ratio OPT/SDP\mathrm{OPT}/\mathrm{SDP}.
QuizWhat depends on UGC?
Which hardness bounds are currently known only assuming the unique games conjecture (in addition to P ≠ NP)?

More than one answer may be correct.

QuizReading a hardness result
Your team uses a solver that always satisfies at least 99 % of clauses on 10 000 production MAX-E3SAT instances. Someone cites Håstad: ‘approximating MAX-E3SAT above 7/8+ε7/8 + \varepsilon is NP-hard.’ What follows?

Summary

Key idea
Approximability is a spectrum: duality, local search and semidefinite programs provide algorithms with provable guarantees, while PCP, gap reductions and the unique games conjecture show that in many problems those guarantees are best possible.
  • Approximation schemes. The knapsack FPTAS scales values using K=εvmax⁡/nK = \eps v_{\max}/n and solves the rounded problem exactly: it loses less than nK≤ε OPTnK \le \eps\,\mathrm{OPT} in time O(n3/ε)\bigO(n^3/\eps). A PTAS may have 1/ε1/\eps in the exponent, and strongly NP-hard problems admit no FPTAS.
  • Primal-dual. Growing a feasible dual and choosing only tight primal variables gives factor β\beta if dual complementary slackness holds with factor β\beta: ff in set cover, 2 in vertex cover, 2 in Steiner tree with reverse pruning. The dual also certifies each instance.
  • Local search. Summing local-optimality inequalities bounds the locality gap: 1/21/2 for MAX-CUT with one vertex, 3+2/p3 + 2/p for k-median with pp swaps. With weights only large improvements should be accepted to ensure polynomial time.
  • Inapproximability. A gap reduction turns an approximation algorithm into a decider. PCP, NP=PCP[log⁡n,1]\mathrm{NP} = \mathrm{PCP}[\log n, 1], is equivalent to a constant gap for MAX-3SAT and rules out a PTAS for all APX-hard problems.
  • Thresholds. 7/87/8 for MAX-E3SAT, ln⁡n\ln n for set cover and 22 for k-center are exact. Goemans–Williamson gives 0.8780.878 for MAX-CUT with an SDP and random hyperplane, and under UGC is optimal, as is 2 for vertex cover.
  • Reading. A hardness result is worst-case, about a specific instance class under a specific assumption: always cite all three.