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
- 08Approximation ratioLP relaxation and deterministic roundingGreedy set cover0/1 knapsack and pseudo-polynomial algorithmsStrong and weak NP-hardnessCook-Levin theoremSAT to 3-SAT reductionDerandomization by conditional expectationsRandomized rounding
- 06Dual problem and weak dualityStrong duality and Slater's conditionComplementary slacknessSemidefinite programmingConvex relaxation
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 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 . Traveling salesperson without the triangle inequality admits no reasonable factor, not even .
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: items with values and weights , capacity , and choose with maximizing . Assume without loss of generality each item fits alone, (discard non-fitting items first). This gives a free lower bound we soon use: .
Dynamic programming by value
Classical dynamic programming indexes capacity and costs . Another, symmetric version indexes value. Let and, for ,
the minimum weight with which the first items reach exactly value ( if unreachable). With and for , the recurrence is the familiar take-or-leave decision for item :
where the second term counts only if . The optimum is the largest with . The table has cells, each filled in constant time: . Like the other algorithm it is pseudopolynomial: polynomial in values, exponential in their number of bits. With six-digit values , the table already has on the order of 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 , measure each value in integer multiples of , and solve the rounded problem exactly.
The new values are small integers: , so and the table has cells, with no trace of . How much is lost? Rounding loses less than one unit per item, . A set has at most items, so rounding changes any set’s value by less than . That is the entire argument, and is chosen so this is exactly .
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 for rounded values (not real ones), loss under per item, and , where the assumption that every item fits alone enters.
On random instances the FPTAS almost always finds optimum even when 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 is in every good solution; ten items are worth almost each but round to ; a decoy is worth slightly more than , rounds to 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 , close to the maximum allowed by the analysis.
Approximation schemes: PTAS and FPTAS
The algorithm above is a family of algorithms, one per , with an explicit accuracy/time tradeoff. The general definition distinguishes time dependence on .
The difference is in the exponent. is an FPTAS. is a PTAS: for each it is a polynomial, but of degree with and degree with . In between is an EPTAS, time , where explosion in is not mixed with .
A PTAS with the exponent in view
Identical-machine scheduling, , distributes jobs with durations across machines to minimize the last completion time (makespan). List scheduling from the previous lesson (assign each job to the least-loaded machine) guarantees factor . Graham (1969) observed that large jobs merely require careful treatment.
Proof
Let be the last-finishing job and the makespan. If is among the large jobs, its machine received no short job afterward (otherwise that would finish after ), so is one machine’s load in the optimal schedule of the large jobs, at most . If is short, when it was placed all machines had load at least its start time , so and . Thus . Finally, the largest jobs are all at least long and in any schedule some machine receives of them: . Combining gives . With , .
∎For fixed this is an approximation scheme (indeed an EPTAS: appears only in constant , not in the exponent of ), and also illustrates why a polynomial guarantee can be useless: with machines and , and assignments must be tried. If is part of the input, ceases to be constant. For that case, Hochbaum and Shmoys (1987) gave a PTAS with in the exponent of , and later Alon, Azar, Woeginger and Yadid (1998) removed 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 .
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 part of the input is one (it contains 3-PARTITION), as is bin packing. Knapsack is not.
The idea: an FPTAS with makes an error smaller than and, since values are integers, makes none. This gives an exact algorithm polynomial in and , 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 is inevitably part of the price.
The primal-dual method
In the previous lesson you obtained factor 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 , and :
By weak duality, every feasible satisfies , where is integer optimum. Complementary slackness conditions say a feasible pair is optimal if and only if and . With integer both cannot be required; the primal-dual method requires the first exactly and relaxes the second.
Proof
By condition 1, , since with contribute nothing to either side. Swapping sum order, by condition 2 ( with contribute nothing). The final inequality is weak duality.
∎This is the primal-dual approximation method: design a process growing while keeping it feasible, adding to only variables whose dual constraints are tight (condition 1), and stopping as soon as is feasible. The approximation ratio is the for which condition 2 can be proved, and certificate comes free: on each instance your solution is within factor of optimum, often much better than .
Set cover
In set cover there is a universe of elements and sets with costs ; frequency is the maximum number of sets containing one element. The LP and its dual are
The dual has an economic reading: each element pays to be covered, and no set can charge its elements more than it costs. The algorithm is a continuous process:
- Start with and no selected sets.
- Grow for all uncovered elements simultaneously at speed 1.
- When a set becomes tight, , add it to the solution: its elements become covered and their freeze.
- 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 stages, each in .
Proof
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 because only sets contain it (condition 2 with ). The previous theorem gives the result.
∎In the initial figure instance (), sets and become tight at , and , and together at . Cost is , dual and integer optimum : the certificate says the solution is within factor of optimum, much better than the guaranteed . Also notice enters with and , 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 . 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: , 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 , increase until or becomes tight. It is linear in graph size and solves no LP.
This analysis cannot improve factor 2, as graph in the figure shows: with unit costs all nine edges rise to , all six vertices become tight simultaneously and the algorithm takes all of them, cost 6 versus optimum 3. The dual is , 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 for any constant 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 and terminal set ; connect terminals by a minimum-cost subgraph that may use nonterminals. The natural LP has one constraint per cut separating terminals: if are edges leaving and contains some but not all terminals, then . There are exponentially many, but primal-dual never writes them. Its dual has a variable per cut, visualized as a moat around : an edge becomes tight when the sum of widths of crossed moats reaches .
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 with edges into two sides, maximizing edges with one endpoint on each side (the cut edges). The local move changes a vertex’s side. If is the degree of and its cut-edge count, moving it changes the cut by : uncut edges become cut and vice versa.
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 . Factor is tight for this neighborhood: in , putting two vertices from each bipartite side on each partition side leaves each vertex with of its edges cut, so moving nobody improves it, and the cut is versus optimum .
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 times its current value: the move count becomes polynomial in , and of total weight, at the cost of guarantee instead of (Kleinberg and Tardos, Algorithm Design, section 12.4).
k-median
In k-median, customers and possible centers lie in a metric space; open 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 centers swapped at once lowers it to , also tightly. For polynomial time, as with weighted MAX-CUT, accept only improvements exceeding a minimum relative factor, at the price of 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 and “no” into ones with , and an approximate algorithm cannot distinguish from . The reduction must open a gap.
Proof
Reduce from Hamiltonian cycle. Given with vertices, construct the complete graph with distance on edges of and on the rest (the number has bits, polynomial). If is Hamiltonian, a cycle of cost exists. Otherwise every cycle uses an edge absent from and costs at least . A -approximation would return a cycle costing exactly when is Hamiltonian.
∎The proof essentially uses distances violating the triangle inequality. With it, metric traveling salesperson admits (Christofides, 1976) and reduction-created gaps are small: the best known hardness is (Karpinski, Lampis and Schmied, 2015). The same technique, with distances and , gives a tight result for k-center (open centers minimizing the maximum distance from a point to its center): a graph has a dominating set of size if and only if the metric “1 on edges, 2 otherwise” has a k-center of radius 1; otherwise radius 2. A factor- 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 : deciding whether numbers fit into 2 bins of capacity 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 , for 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 is easy: with 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 the problem of distinguishing satisfiable 3CNF formulas from formulas where every assignment satisfies at most fraction of clauses (promising the input is one of the two types).
Proof
(2 ⇒ 1). Let be NP and the reduction from to . Given , the verifier computes with clauses, interprets as an assignment to its variables, chooses a random clause ( bits), reads its 3 variables and accepts if satisfied. If , the satisfying assignment makes it always accept. Otherwise every assignment fails on at least fraction of clauses, so the verifier rejects with probability at least . Repeating times with independent clauses drops acceptance probability to , with queries (a constant) and random bits.
(1 ⇒ 2). Let be NP-complete with a verifier using random bits and reading bits, with constant. For each random string , the queried positions and verifier decision are determined, so “ accepts with string ” is a Boolean function of bits of . Write it as a CNF with at most clauses (one per rejected bit combination) and convert it to 3CNF using auxiliary variables as in the SAT to 3SAT reduction, with at most clauses. Formula is the conjunction over all : clauses, polynomially many. If , the always-accepting proof (plus correct auxiliary values) satisfies . If , for every assignment (every ), at least half of reject, and each leaves at least one clause in its group unsatisfied. The unsatisfied fraction is at least ; choose .
∎An -approximation on a satisfiable formula would return an assignment with more than clauses satisfied, impossible for the other instance type: it would decide . 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 , so satisfies clauses in expectation, and derandomization by conditional expectations makes this deterministic. Håstad proved doing better impossible: for every , distinguishing satisfiable formulas from those where at most fraction 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 . Feige proved that, for every , no -approximation exists unless NP DTIME, a somewhat stronger assumption than P ≠ NP. Dinur and Steurer weakened it to P ≠ NP: approximation below 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 ) cuts edges in expectation, like local search. For nearly twenty years nobody knew how to guarantee a constant above . Goemans and Williamson (1995) achieved it by going beyond linear programming.
The Goemans–Williamson algorithm
With weights and indicating sides, an edge is cut if , so
The relaxation replaces each number by a unit vector and the product by the dot product:
This is a convex relaxation. A relaxation because recovers any cut, so . Convex, despite appearances: with Gram matrix , the problem maximizes a linear function of subject to and , a semidefinite program solvable to accuracy in polynomial time. Vectors are recovered from by Cholesky factorization. The rounding is randomized, but geometric: take a random hyperplane through the origin with normal , and place vertices according to which side their vectors fall on, .
Proof
Only the projection of onto the plane generated by and matters, because . The standard Gaussian is rotation-invariant, so is a standard Gaussian in the plane and its direction is uniform on the circle. Signs of and differ exactly when the direction of lies in one of the two opposite arcs between perpendiculars to and , each of length . The probability is . (The probability that is zero or perpendicular to either is zero.)
∎Proof
By linearity of expectation and the previous theorem, . By definition of , for every and also , where both sides are zero. With and , summing gives .
∎You will compute the numerical value of and its minimizing angle in the exercises. Three qualifications. The SDP is solved to arbitrarily small additive error, so the actual guarantee is ; repeated rounding gives high probability, and derandomization exists (Mahajan and Ramesh, 1999). Assumption 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 over graphs, is exactly (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: with SDP, and best NP hardness (Håstad, 2001, with a gadget by Trevisan, Sorkin, Sudan and Williamson, 2000). Vertex cover is similar: 2 by primal-dual versus known NP-hard (Khot, Minzer and Safra, 2018; previously 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 and not : if all constraints can be satisfied, fix one vertex label per component (trying the possibilities) and propagate it in polynomial time. A concrete example is systems of equations : 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 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 would cease to be an analysis artifact and become a constant of nature.
- Vertex cover: 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 from near-zero value is NP-hard. From that proof comes 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.
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 ( versus , versus ): 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 , approximating within factor is NP-hard” has four parts to check:
- Assumption. P ≠ NP, NP DTIME, NP ≠ ZPP, UGC and the exponential-time hypothesis differ. A “under UGC” result may fall if the conjecture does.
- 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.
- 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 , but does admit (Fernandez de la Vega and Lueker, 1981).
- Quantifiers. “For every ” versus “for some ”, and whether depends on .
Lab: FPTAS, primal-dual and local search
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 , with six-digit values.
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 is , far from promised , and at the worst ratio already rounds to . Table size grows as theory predicts: from about cells at to about at , factor for ratio in , below bound . Unscaled, the same DP would need about 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 sets. Compare cost with its constructed dual, integer optimum (scipy.optimize.milp) and LP optimum (linprog).
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 , substantially: at most , and for . The true ratio against optimum is smaller still (, and 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 , and here. Reverse pruning helps more as grows because more overlap adds redundant sets: worst ratio drops from to at and from to at .
Finally local search for MAX-CUT, from 10 random partitions on each of 20 random graphs , versus exact brute-force maximum (vectorized over cuts fixing vertex 0), and the worst case of .
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 , as the theorem guarantees, but on these graphs none approaches it: worst cuts times , and worst ratio against exact optimum is , far from the theorem’s . At most 9 moves are needed on graphs with up to 38 edges: the -move bound is pessimistic. And shows is tight: the initial partition is already locally optimal, 0 moves, cut and optimum .
Goemans–Williamson versus local search
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 with small . MAX-CUT has a simple coordinate update. Fixing other vectors, the objective depends on through , maximized over the unit sphere at with . 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 ( is positive definite), strong duality holds and this bound can be exact. The dual of with and , where is the weighted Laplacian, is subject to . Any feasible upper-bounds the SDP because . Take suggested by complementary slackness, , and if has a negative eigenvalue , subtract from every to make it feasible.
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 to four decimal places, so mixing found the SDP optimum: no cut in this graph exceeds edges. The random hyperplane cuts on average, of SDP, above guarantee ; the best of 200 samples cuts 147. Local search from 30 random partitions is slightly lower on average () and its best result, 146, is nearly the same.
Local search competing well on a random graph contradicts nothing: 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 ; the SDP certifies nothing exceeds , so the best cut found, 147, is within of optimum. In the worst case the hyperplane guarantees where local search guarantees only , as in , 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 . 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.
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)}")npm run lab and open the connection link.CVXPY (with Clarabel solver) gives the same value , confirming the previous cell’s certificate. The hyperplane on its solution cuts 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 applies to any optimal solution; which rounds better on a particular instance is empirical.
Typical mistakes
Exercises
Step 1 of 5. What is the first useful inequality?
More than one answer may be correct.
Step 1 of 4. What do you choose for each instance ?
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 with neither endpoint in the cover, increase as far as possible, until or becomes tight (), 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 .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, yStep 1 of 3. What does local optimality say at vertex ?
More than one answer may be correct.
Summary
- Approximation schemes. The knapsack FPTAS scales values using and solves the rounded problem exactly: it loses less than in time . A PTAS may have 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 if dual complementary slackness holds with factor : 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: for MAX-CUT with one vertex, for k-median with 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, , is equivalent to a constant gap for MAX-3SAT and rules out a PTAS for all APX-hard problems.
- Thresholds. for MAX-E3SAT, for set cover and for k-center are exact. Goemans–Williamson gives 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.