Approximation algorithms: greedy and LP rounding
When the optimum cannot be obtained, proximity can be guaranteed. Define approximation ratios and learn to bound the unknown optimum. Study 2-approximations for vertex cover via matching and linear relaxation rounding, greedy set cover with factor H_n and randomized rounding, metric traveling salesperson with doubled spanning tree and Christofides, k-center, and Graham's parallel machine scheduling.
After this lesson you can
- Prove approximation factors by comparison with lower bounds on the optimum.
- Design 2-approximations for vertex cover using matching and linear relaxation rounding.
- Prove the H_n factor for greedy set cover and apply randomized rounding.
- Implement doubled spanning tree and Christofides for metric traveling salesperson.
- Analyze Gonzalez's k-center algorithm and Graham's scheduling and LPT.
Before you start
- 08NP-hardness and NP-completenessIndependent set, clique and vertex coverHamiltonian cycle and TSPKruskal algorithmEdmonds blossom algorithmGreedy paradigmProbability amplificationBipartite matching via augmenting paths
- 06Linear programmingConvex relaxation
- 04Chernoff boundMultiplicative Chernoff boundsUnion bound
Motivation: guaranteeing quality without knowing the optimum
Three everyday engineering problems:
- Deploy sensors. You have points to monitor and candidate locations, each with its cost and the set of points it reaches. Cover all points at minimum cost. If instead you have exactly sensors and want the worst-served point as close as possible to one, the problem changes shape but not difficulty.
- Select tests. A continuous integration suite has hundreds of tests, each exercising a subset of project functions. Find the cheapest subset (by count or CI seconds) still exercising every function at least once.
- Distribute jobs over a cluster. You have jobs of known duration and identical machines. Make the last job finish as early as possible.
All three are NP-hard. The first and second are set cover instances, which contain vertex cover from the independent-set family; the version with sensors is k-center, which contains dominating set; the third contains partition with and is strongly NP-hard when is part of the input. By NP-completeness theory, we do not expect an exact polynomial algorithm for any of them.
The previous lesson answered by giving up polynomial time: exact algorithms exploiting structure. This lesson gives up exactness, but not a guarantee. An approximation algorithm is polynomial and proves its solution is within a factor of the optimum on every input. The important word is “proves”: the optimum is unknown and the guarantee must come from reasoning that bounds it without computing it. The techniques are few and recur: greedy arguments compared with a combinatorial lower bound, linear relaxations rounded, and packing arguments. Everything that follows is a variation on that idea.
Approximation ratio and lower bounds on the optimum
Fix a minimization problem: each instance has a set of feasible solutions, each solution has cost , and is the minimum. Algorithm returns a feasible solution .
Three nuances. This is a worst-case guarantee: an algorithm returning the optimum on 99.9 % of instances and on the rest is a 3-approximation, not a 1.001-approximation. It is multiplicative: additive guarantees () exist but are rare for NP-hard problems. And the factor is a property of the algorithm with its analysis, not the problem: the property of the problem is the best achievable factor, and determining that number occupies half the field.
The invisible optimum problem
To prove you cannot compute : if you could, approximation would not be needed. The pattern of almost all proofs is to find a quantity with two properties:
Prove the first by looking at an arbitrary optimal solution without knowing it: “let be optimal; then must…”. Prove the second by looking at what the algorithm does. The art is choosing : too small and the second inequality fails; too large and the first is false. These are the ones used in the lesson:
| Problem | Lower bound | Why it is a bound | Factor obtained |
|---|---|---|---|
| Vertex cover | matching size | every matching edge needs its own vertex | |
| Weighted cover | linear relaxation optimum | every integer solution is fractional | |
| Set cover | (and prices bounding it) | same | |
| Metric traveling salesperson | minimum spanning tree; half a matching | a cycle minus one edge is a tree | and |
| k-center | points separated by | two share an optimal ball | |
| Scheduling on machines | some machine bears average load; the largest job goes whole | and |
Each row is a section of the lesson. The ratio on the worst instance limits what any analysis based on can prove; when is a relaxation value, that ratio has a name (the integrality gap) and you will see it live in the first figure.
How well can problems be approximated?
NP-hardness says nothing about approximability, and the problems here span the spectrum. Parallel-machine scheduling allows factors arbitrarily close to 1 (an approximation scheme, the subject of the next lesson). Vertex cover and k-center have factor 2: for k-center it is proved that no improvement is possible unless P = NP, and for cover this is conjectured. Set cover allows and no better. Traveling salesperson without the triangle inequality admits no constant factor. Lower bounds come from gap-preserving reductions and the PCP theorem, seen next lesson; here we prove only the two fitting in a paragraph (traveling salesperson and k-center) and cite the rest.
Vertex cover: maximal matching
A vertex cover of a graph is a touching every edge: for each , or . Finding the smallest is NP-hard because its complement is a maximum independent set.
A matching is a set of edges with no common endpoints; it is maximal if no edge can be added (do not confuse with maximum, of largest cardinality, computed using augmenting paths in bipartite graphs and the blossom algorithm in general). A maximal matching is obtained greedily: traverse edges and retain each that shares no endpoint with those chosen.
Proof
Feasibility. If an edge had no endpoint in , it would share none with any edge of and could be added to , contradicting maximality.
Lower bound. Let be an optimal cover. Each edge of has an endpoint in , and as edges of share no endpoints, those vertices are distinct: . Therefore .
∎The lower bound is , and the analysis is tight: in complete bipartite any maximal matching is perfect, the algorithm returns all vertices, and an optimal side has . Using a maximum rather than maximal matching does not help: is the same counterexample.
Can 2 be improved? Nobody knows how by a constant. Dinur and Safra (2005) proved that, unless P = NP, no factor better than exists; Khot, Minzer and Safra (2018) raised that bound to ; and Khot and Regev (2008) proved that, if the unique games conjecture holds, no polynomial algorithm goes below . The two-line algorithm would then be optimal.
Linear relaxation and rounding
Matching does not work if vertices have weights : a vertex of weight at an endpoint of an edge of is included anyway. The general tool is linear programming. Write the problem as an integer program with a variable per vertex and relax integrality, a convex relaxation:
Every cover is a solution of the program on the right, so . This inequality is the lower bound, and it has an advantage matching lacked: it is computable in polynomial time, giving a numerical certificate of how far you can be from the optimum on your specific instance.
The fractional solution is not a cover, but can be rounded. This problem’s relaxation has a strong property proved in the previous lesson while constructing the linear kernel: its vertices have coordinates in (Nemhauser and Trotter, 1975; the proof does not use weights). Rounding does not need it, but it explains what the figure shows.
Proof
Feasibility. For each edge, , so and one endpoint belongs to .
Cost. For , . Then , where the last inequality uses .
∎This is the linear relaxation rounding pattern: (1) formulate an integer program, (2) solve the relaxation, giving , (3) convert into a feasible integer solution losing at most factor relative to . Steps (2) and (3) are proved separately, and (3) always has two parts: feasibility and cost.
In the initial graph, : half per vertex in the triangle () and pentagon (), and on the hub, with its leaf at 0. The integer optimum is because a triangle needs 2 vertices and a pentagon 3, and the hub must be included to cover its leaf (or the leaf to cover it). Rounding includes the eight half-valued vertices and the hub: . Chain is exactly the theorem’s and teaches two things. First, rounding may be far from optimal () even when the relaxation is close (): the loss comes from rounding, not the bound. Second, at ‘Umbral = 1’ the cost falls to 1 and appears better than optimal, but is not a cover. In the bipartite graph the relaxation is integral (total unimodularity of the bipartite incidence matrix, the same reason maximum flow has integer solutions), and the gap is 1.
In the relaxation puts at all vertices (), while a cover needs vertices (omitting two leaves their edge uncovered). The gap is , tending to 2: no analysis using this relaxation can go below factor 2. To do so one would need to strengthen it with valid integer inequalities, e.g. for each clique . Even that does not suffice in general: Charikar, Makarychev and Makarychev (2009) proved that the Sherali–Adams hierarchy, which systematically adds such inequalities, retains a gap of after rounds, with depending on .
Set cover
A universe of elements, a family whose union is , and costs . A cover is a with ; the goal is minimum cost . Vertex cover is the case where elements are edges and each vertex is the set of its incident edges: each element is in exactly two sets. Sensors and test selection are set covers directly.
Greedy and its prices
The greedy rule is the usual one in the greedy paradigm, with a well-chosen performance measure: at each step select the set with least cost per new element, , where is what is already covered. This is Johnson’s (1974) and Lovász’s (1975) greedy set cover for unit costs, and Chvátal’s (1979) for costs.
To analyze it, imagine greedy charges its cost to the elements it covers: if it chooses and it covers new elements, each pays a price . The sum of prices is exactly greedy’s cost, so it suffices to bound each price. Number elements in coverage order (those in the same step in any order).
Part (b) follows by summing (a). The lemma is an averaging argument over sets in an optimal solution, which you will reconstruct step by step in the first guided exercise; first, the figure lets you see the inequality at every step.
In the initial instance (24 points, 12 unit-cost disks), greedy uses 9 sensors and the brute-force optimum 8: ratio , far from . The bars remain far below the bound, and the largest price/bound ratio shown is a fraction of 1. ‘Instancia mala’ shows the logarithm is real: two rows and of points and blocks of sizes crossing both rows. The optimum is , costing 2. But the largest block covers elements versus for a row, so greedy prefers it; the same happens at every step, so it pays . With elements, the ratio is . With costs exactly is achieved: elements , a singleton of cost , and the entire universe costing . When elements remain uncovered (the ), the cheapest singleton is with ratio , beating the universe’s ; greedy chooses it and continues, paying versus ; you will check this in the lab.
And essentially no better is possible. Feige (1998) proved approximating within would imply , and Dinur and Steurer (2014) obtained the same threshold under P NP. The three-line greedy algorithm is, up to lower-order terms, the best possible polynomial algorithm.
Prices as a dual solution
The lemma compares with ; a finer argument compares with and gives a better bound for small sets. The set cover relaxation and its dual are
By weak duality, any dual-feasible satisfies . Prices are almost a dual solution: they can exceed a set’s cost. But only slightly.
Proof
Fix a set with elements and order them by when greedy covers them. Just before the step covering , elements remain uncovered, so offered at least new elements for cost , and greedy chose something equally cheap or cheaper per element: . Summing, , the dual constraint of for . Since prices sum to greedy’s cost, that cost is .
∎This technique (the algorithm simultaneously constructs an integer solution and an “almost feasible” dual one, and the factor is how much to scale the dual) is called dual fitting, and leads to the primal-dual method in the next lesson. In vertex cover is maximum degree , so greedily choosing a maximum-degree vertex is an -approximation, and graphs exist where it loses a logarithmic factor: maximal matching, which looks more foolish, is better.
Frequency rounding and randomized rounding
Two ways to round the set cover relaxation complete the picture.
Threshold . If each element belongs to at most sets, each constraint has at most variables summing to at least 1, so one is at least . Selecting is feasible and costs at most by the same argument as vertex cover, the case. This is good when is small and useless otherwise.
Randomized rounding. Interpret as a probability. Randomized rounding (Raghavan and Thompson, 1987) takes an optimal solution and repeats independent rounds; in each, include each with probability .
Proof
Cost. In each round expected cost is ; in rounds, at most (a set selected twice is paid once). By Markov’s inequality, .
Coverage. An element remains uncovered in one round with probability , using and the constraint for . Rounds are independent, so it remains uncovered at the end with probability . By the union bound, some of the elements remains uncovered with probability .
The two bad events together have probability .
∎If it fails, repeat: the expected attempts are at most 2 and the probability of failing times in a row is , the usual amplification. Checking feasibility and cost is trivial, so this is a Las Vegas algorithm. It can also be derandomized using conditional expectations.
Factor is worse in its constant than greedy’s . The interest is generality: it works with multicover constraints (), capacity-limited sets or, in the original work, packet routing minimizing link congestion. There the relevant random variable is a sum of independent indicators (link load), and the tool is the multiplicative Chernoff bound combined with the union bound: if expected link load is , the Chernoff method gives , which with drops below ; the union bound over links closes the argument, and congestion is times the fractional value.
Traveling salesperson: impossible in general, approximable with a metric
Traveling salesperson asks for a minimum-length Hamiltonian cycle in a complete graph with weights ; its decision version is NP-complete because it contains Hamiltonian cycle. That reduction says something stronger.
The proof is a gap-creating reduction: instances from Hamiltonian graphs have optimum , and the others have optimum greater than . You will do it in the third guided exercise. The ingredient needed to escape is the triangle inequality, : traveling salesperson with it is metric traveling salesperson. Its key consequence is that shortcuts do not lengthen: if a closed walk visits all vertices, perhaps repeatedly, and you skip repeats, each shortcut replaces a path by edge , no longer than the path.
The doubled spanning tree
An optimal Hamiltonian cycle without one edge is a spanning tree, so the minimum spanning tree (computed with Kruskal or Prim) satisfies , with nonnegative weights. Double every edge of : all degrees are even and the multigraph is connected, so it has an Eulerian circuit of length visiting every vertex. Shortcut repeats: the result is the preorder traversal of .
The proof is the previous three sentences in order; you will reconstruct it in the second guided exercise, including errors that arise when a hypothesis is skipped.
Christofides: fix only odd degrees
Doubling is wasteful: only odd-degree vertices prevent an Eulerian circuit and need fixing. Christofides (1976), independently Serdyukov (1978), observed it suffices to add a matching among them.
Proof
Let be an optimal cycle.
Tree. Removing an edge of leaves a spanning tree, so .
Matching. Traverse and keep only vertices in , in order: by the triangle inequality, that cycle over has length at most . Since is even, alternating edges divide into two perfect matchings of . Their weights sum to at most , so the lighter weighs at most , as does the minimum : .
Circuit and shortcuts. is connected (it contains ) and every vertex has even degree (those in gain one edge; the rest none). Its Eulerian circuit has length , and shortcutting does not lengthen it by the triangle inequality.
∎This is the central result of metric traveling salesperson approximation. Notice where each hypothesis is used: the triangle inequality appears twice (in the shortcut cycle over and in final shortcuts), and positive weights in the first bound.
In the initial instance, , and Christofides has length , versus optimum : . The doubled tree gives , . On the circle the minimum tree is a path around the contour, only its endpoints have odd degree, and the matching is the edge closing the contour: Christofides returns the optimum, while doubled-tree preorder, starting at an interior path vertex, usually has to retrace its steps (with nine cities, ; with five or six, preorder happens to be optimal).
For 45 years nobody improved for general metric traveling salesperson. Karlin, Klein and Oveis Gharan (2021) reduced it to with , replacing the minimum tree with a random tree drawn from the traveling salesperson linear relaxation: an important theoretical, not practical, advance. From below, Karpinski, Lampis and Schmied (2015) proved that approximating metric traveling salesperson within a factor below is NP-hard. The gap between and remains open. In the Euclidean plane the situation is much better: an approximation scheme achieves for any fixed (Arora, 1998; Mitchell, 1999); schemes are the next lesson’s subject.
k-center: the farthest point
Given points with a distance satisfying the triangle inequality and integer , k-center seeks centers minimizing radius , where : the worst distance from a point to its closest center. This is deployment of sensors, warehouses or service replicas when the worst case matters, not the mean.
Gonzalez’s algorithm (1985) is farthest-first traversal: choose any first center and, while there are fewer than , add the point farthest from the chosen centers. With precomputed distances it costs .
Proof
Let be centers in selection order and the final farthest point, with .
Separation. When () was chosen, its distance to predecessors was and it was the farthest point. Each point’s distance to centers can only decrease when centers are added, so the final maximum does not exceed the maximum at that moment: . Therefore for , and by definition of . The points are pairwise separated by at least .
Packing. An optimal solution has centers and every point is within of one. By the pigeonhole principle, two of those points, and , share an optimal center , and .
∎The lower bound here is not a relaxation but a packing: widely separated points force any solution with balls to have large radius. Factor 2 is the best possible:
Proof
Reduce from dominating set: given a graph and , is there with such that every vertex is in or adjacent to one in ? It is NP-complete. Define if , if are not adjacent, and . This is a metric because . If has a dominating set of size , k-center with centers in has radius 1; otherwise any choice of centers leaves a vertex at distance 2 and optimum is 2. A -approximation would return radius , i.e. 1, in the first case and 2 in the second, deciding dominating set in polynomial time.
∎These two theorems form k-center approximation: a two-line algorithm with the exact factor complexity allows. Hochbaum and Shmoys (1985) obtained the same factor with another algorithm based on trying candidate radii.
With three groups and , Gonzalez has radius and optimum : ratio , not small. On real data Gonzalez often stays far from optimal, and its weakness appears with an outlier: the farthest point is, by construction, the rarest, and the algorithm devotes an entire center to it. This is not an analysis failure, because radius is the worst distance: if one isolated point matters as much as all others, the objective dictates this.
Relationship to k-means++
k-means++ initialization (Arthur and Vassilvitskii, 2007) is a randomized version of the same traversal: instead of the farthest point, it chooses each new center with probability proportional to . The objective differs, k-means’ sum of squared distances rather than maximum, and sampling is exactly what it needs: far points are more likely, but a lone outlier weighs little against an entire group. Arthur and Vassilvitskii proved the expected cost of initial centers is at most times the k-means optimum, an expected -approximation before any Lloyd iteration. Note is not a metric (it violates the triangle inequality, as just seen), so k-means++ analysis needs a relaxed form.
Parallel-machine scheduling
You have jobs with durations and identical machines. Each job runs whole on one machine, whose load is the sum of its jobs. The goal is to minimize makespan , the largest load, i.e. the time the last job finishes (scheduling notation ). Two lower bounds are obvious: some machine bears at least the average, and the largest job runs whole on one machine:
Graham’s (1966) list scheduling is the simplest conceivable greedy rule: traverse jobs in the given order and assign each to the currently least-loaded machine. With a load heap it costs .
Proof
Let be a job finishing last, at time . When assigned, it went to the least-loaded machine, whose load was ; all others had load at least , and all those loads consisted of jobs other than . Thus , and
using the two lower bounds, one for each term.
∎This is the list scheduling algorithm, and the proof shows where the loss arises: the last job, which may arrive when all machines are balanced. An instance of unit jobs followed by one of size exploits this: the list distributes unit jobs ( per machine) then adds the large one to a machine, , while optimum puts the large one alone and units on the other machines, . Ratio exactly meets the bound. An important detail: list scheduling never looks at future jobs, so it is also an online algorithm with competitive ratio .
LPT: largest first
If all jobs are known beforehand, the bad instance suggests a fix: prevent large jobs arriving last. LPT (longest processing time first) sorts jobs descending and applies list scheduling.
Proof
Number jobs in descending order, , and let finish last. LPT assigns jobs identically with or without later ones, and removing jobs cannot increase optimum; so it suffices to prove the bound for instance and its optimum . Call the smallest job, the LPT makespan, and that instance’s optimum.
Case . Graham’s argument gives .
Case . Then every job exceeds , and no optimal machine has three. We show LPT is optimal: suppose . If any machine was empty when was assigned, ; so all had at least one job. Let count machines with exactly one; the other had at least two, so . A machine with one job had load : call a job large if ; there are . In the optimum, a large job cannot share a machine (any other job has size at least and the sum exceeds ), so occupies one alone, and the remaining fit two per machine in the other : , i.e. . Contradiction.
Tightness. With machines and jobs , the optimum pairs with () and puts the three of size together: . LPT distributes the first in pairs on each machine, all reach load , and the final job of size finishes at . The ratio is .
∎With , Graham’s instance gives makespan 7 by list versus optimum 4 (), and LPT solves it exactly. The LPT instance with gives 15 versus 12, ratio . For this problem the story does not end at : Hochbaum and Shmoys (1987) gave an approximation scheme reaching for any fixed , the central PTAS example of the next lesson.
Lab: approximations with measured guarantees
Time to measure. The cells implement each algorithm from scratch and compare it with the exact optimum on small instances, computed using the integer solver scipy.optimize.milp (HiGHS), Held–Karp (subset dynamic programming), or enumeration. Two things matter: no ratio exceeds its guarantee, and how far it typically stays from it.
import numpy as np
import networkx as nx
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
def vc_emparejamiento(n, aristas):
"""2-aproximación: los extremos de un emparejamiento maximal construido de forma voraz."""
cubierto = np.zeros(n, dtype=bool)
for u, v in aristas:
if not cubierto[u] and not cubierto[v]:
cubierto[u] = cubierto[v] = True
return np.flatnonzero(cubierto)
def incidencia(n, aristas):
A = np.zeros((len(aristas), n))
for k, (u, v) in enumerate(aristas):
A[k, u] = A[k, v] = 1
return A
def vc_redondeo(n, aristas, w):
"""Relajación lineal con HiGHS y redondeo a 1/2, comprobando la factibilidad."""
r = linprog(w, A_ub=-incidencia(n, aristas), b_ub=-np.ones(len(aristas)), bounds=(0, 1), method="highs")
S = np.flatnonzero(r.x >= 0.5 - 1e-9) # tolerancia: el solucionador puede devolver 0.4999999999
dentro = np.zeros(n, dtype=bool); dentro[S] = True
assert all(dentro[u] or dentro[v] for u, v in aristas), "el redondeo no es un recubrimiento"
return S, r.fun, r.x
def vc_exacto(n, aristas, w):
r = milp(w, constraints=LinearConstraint(incidencia(n, aristas), lb=1), integrality=np.ones(n), bounds=Bounds(0, 1))
return r.fun
rng = np.random.default_rng(1)
r_emp, r_red, brecha, r_w, r_nx, valores = [], [], [], [], [], set()
for _ in range(30):
n = 16
E = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.25]
uno = np.ones(n)
opt = vc_exacto(n, E, uno)
S2, lp, x = vc_redondeo(n, E, uno)
valores |= {float(abs(round(t, 6))) for t in x}
r_emp.append(len(vc_emparejamiento(n, E)) / opt)
r_red.append(len(S2) / opt)
brecha.append(opt / lp)
w = rng.integers(1, 11, n).astype(float) # con pesos, el emparejamiento ya no sirve
S3, _, _ = vc_redondeo(n, E, w)
opt_w = vc_exacto(n, E, w)
r_w.append(w[S3].sum() / opt_w)
G = nx.Graph(E); nx.set_node_attributes(G, dict(enumerate(w)), "w")
S4 = nx.algorithms.approximation.min_weighted_vertex_cover(G, weight="w")
r_nx.append(w[list(S4)].sum() / opt_w)
print("30 grafos G(16, 0.25):")
print(f" emparejamiento / OPT: media {np.mean(r_emp):.3f}, máximo {np.max(r_emp):.3f}")
print(f" redondeo LP / OPT: media {np.mean(r_red):.3f}, máximo {np.max(r_red):.3f}")
print(f" OPT / LP* (brecha): media {np.mean(brecha):.3f}, máximo {np.max(brecha):.3f}")
print(f" con pesos, redondeo / OPT: media {np.mean(r_w):.3f}, máximo {np.max(r_w):.3f}")
print(f" con pesos, networkx / OPT: media {np.mean(r_nx):.3f}, máximo {np.max(r_nx):.3f}")
print(" valores que toma x en las soluciones de HiGHS:", sorted(valores))
for n in [4, 6, 8, 10]:
E = [(u, v) for u in range(n) for v in range(u + 1, n)]
_, lp, _ = vc_redondeo(n, E, np.ones(n))
opt = vc_exacto(n, E, np.ones(n))
print(f"K_{n}: LP* = {lp:.1f}, OPT = {opt:.0f}, brecha = {opt / lp:.3f}")Three observations. First: on these graphs the guarantee is not a pessimistic bound. Both algorithms reach exactly 2 on the worst of 30 graphs and lose nearly 60 % on average ( and ). Integer optimum is close to (mean gap , maximum ), so the loss is rounding, which raises all halves to 1, as in the figure. Second: HiGHS returns values in , as half-integrality predicts, because its method ends at a polytope vertex. Third: with weights, rounding loses 53 % on average and the networkx function 41 %. That function implements another 2-approximation, Bar-Yehuda and Even’s (1985) local-ratio algorithm, without solving a linear program; same guarantee, different typical behavior. The gaps of reproduce .
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
def voraz_cobertura(n, conjuntos, costes):
"""Chvátal: el conjunto de menor coste por elemento nuevo. Devuelve los elegidos, los precios y el orden."""
sin_cubrir = set(range(n))
elegidos, precio, orden = [], np.zeros(n), []
while sin_cubrir:
utiles = [i for i in range(len(conjuntos)) if conjuntos[i] & sin_cubrir]
i = min(utiles, key=lambda i: costes[i] / len(conjuntos[i] & sin_cubrir))
nuevos = conjuntos[i] & sin_cubrir
for e in sorted(nuevos):
precio[e] = costes[i] / len(nuevos)
orden.append(e)
sin_cubrir -= nuevos
elegidos.append(i)
return elegidos, precio, orden
def matriz(n, conjuntos):
A = np.zeros((n, len(conjuntos)))
for j, S in enumerate(conjuntos):
A[list(S), j] = 1
return A
def cobertura_lp(n, conjuntos, costes):
r = linprog(costes, A_ub=-matriz(n, conjuntos), b_ub=-np.ones(n), bounds=(0, 1), method="highs")
return r.x, r.fun
def cobertura_exacta(n, conjuntos, costes):
r = milp(costes, constraints=LinearConstraint(matriz(n, conjuntos), lb=1),
integrality=np.ones(len(conjuntos)), bounds=Bounds(0, 1))
return r.fun
def redondeo_aleatorizado(n, conjuntos, x, rng, rondas):
"""t rondas; en cada una entra S_j con probabilidad x_j. Se repite hasta cubrir (Las Vegas)."""
intentos = 0
while True:
intentos += 1
elegido = np.zeros(len(conjuntos), dtype=bool)
for _ in range(rondas):
elegido |= rng.random(len(conjuntos)) < x
if len(set().union(*(conjuntos[j] for j in np.flatnonzero(elegido)))) == n:
return np.flatnonzero(elegido), intentos
def instancia_azar(n, m, rng):
conjuntos = [set(rng.choice(n, size=rng.integers(3, 13), replace=False).tolist()) for _ in range(m)]
for e in range(n):
if not any(e in S for S in conjuntos):
conjuntos[rng.integers(m)].add(e)
costes = np.array([1.0 + 0.25 * len(S) + rng.random() for S in conjuntos])
return conjuntos, costes
rng = np.random.default_rng(0)
n, m = 40, 30
rondas = int(np.ceil(np.log(4 * n)))
filas = []
for _ in range(12):
C, c = instancia_azar(n, m, rng)
opt = cobertura_exacta(n, C, c)
x, lp = cobertura_lp(n, C, c)
G, precio, orden = voraz_cobertura(n, C, c)
lema = max(precio[e] * (n - k) / opt for k, e in enumerate(orden)) # k desde 0: cota OPT/(n - k)
R, intentos = redondeo_aleatorizado(n, C, x, rng, rondas)
f = int(matriz(n, C).sum(axis=1).max())
U = np.flatnonzero(x >= 1 / f - 1e-9)
filas.append((c[G].sum() / opt, c[R].sum() / opt, intentos, c[U].sum() / opt, opt / lp, lema, f))
F = np.array(filas)
print(f"12 instancias con n = {n} elementos y m = {m} conjuntos; redondeo con {rondas} rondas:")
print(f" voraz / OPT: media {F[:, 0].mean():.3f}, máximo {F[:, 0].max():.3f} (H_40 = {sum(1 / k for k in range(1, 41)):.2f})")
print(f" redondeo aleatorizado / OPT: media {F[:, 1].mean():.3f}, máximo {F[:, 1].max():.3f}, intentos medios {F[:, 2].mean():.2f}")
print(f" umbral 1/f / OPT: media {F[:, 3].mean():.3f}, máximo {F[:, 3].max():.3f} (f entre {F[:, 6].min():.0f} y {F[:, 6].max():.0f})")
print(f" OPT / LP*: media {F[:, 4].mean():.3f}, máximo {F[:, 4].max():.3f}")
print(f" lema: máximo de precio_k (n - k + 1) / OPT = {F[:, 5].max():.3f}")
for n in [10, 100]: # la instancia ponderada en la que el voraz paga exactamente H_n
C = [{e} for e in range(n)] + [set(range(n))]
c = np.array([1 / (e + 1) for e in range(n)] + [1.001])
G, _, _ = voraz_cobertura(n, C, c)
print(f"instancia de H_n, n = {n}: voraz {c[G].sum():.4f}, OPT {cobertura_exacta(n, C, c):.4f}, H_n = {sum(1 / k for k in range(1, n + 1)):.4f}")Greedy loses 13.5 % on average (22 % worst case) against a guarantee , and the lemma line confirms no price exceeds its bound (maximum ). Randomized rounding instead pays times optimum on average, and threshold with frequencies 9 to 14 pays times: their guarantees are worse than greedy’s, and so is their behavior here. Randomized rounding losing to greedy is no contradiction: with constant 4 is worse than , and the algorithm as written includes many redundant sets (the next lab prunes them). The last line is the tight instance: greedy pays exactly versus optimum .
import numpy as np
import networkx as nx
def distancias(P):
return np.sqrt(((P[:, None, :] - P[None, :, :]) ** 2).sum(-1))
def prim(D):
n = len(D)
dentro = np.zeros(n, dtype=bool); dentro[0] = True
mejor, padre, arbol = D[0].copy(), np.zeros(n, dtype=int), []
for _ in range(n - 1):
v = int(np.argmin(np.where(dentro, np.inf, mejor)))
arbol.append((int(padre[v]), v)); dentro[v] = True
cerca = D[v] < mejor
mejor, padre = np.where(cerca, D[v], mejor), np.where(cerca, v, padre)
return arbol
def longitud(ciclo, D):
return sum(D[ciclo[i], ciclo[(i + 1) % len(ciclo)]] for i in range(len(ciclo)))
def atajar(paseo):
visto, ciclo = set(), []
for v in paseo:
if v not in visto:
visto.add(v); ciclo.append(v)
return ciclo
def arbol_doblado(D):
"""El preorden del árbol mínimo es el circuito del árbol doblado ya atajado."""
return list(nx.dfs_preorder_nodes(nx.Graph(prim(D)), 0))
def christofides(D):
n = len(D)
T = prim(D)
grado = np.bincount(np.array(T).ravel(), minlength=n)
impares = [v for v in range(n) if grado[v] % 2]
K = nx.Graph()
K.add_weighted_edges_from((u, v, D[u, v]) for i, u in enumerate(impares) for v in impares[i + 1:])
M = nx.min_weight_matching(K) # perfecto: K es completo con un número par de vértices
G = nx.MultiGraph(T); G.add_edges_from(M)
ciclo = atajar([u for u, _ in nx.eulerian_circuit(G, source=0)])
return ciclo, sum(D[u, v] for u, v in T), sum(D[u, v] for u, v in M)
def held_karp(D):
"""Óptimo exacto en O(2^n n^2): dp[S, j] = camino mínimo desde 0 que visita S y acaba en j."""
n = len(D)
N = 1 << (n - 1)
dp = np.full((N, n - 1), np.inf)
for j in range(n - 1):
dp[1 << j, j] = D[0, j + 1]
Dm = D[1:, 1:]
for S in range(1, N):
fuera = [k for k in range(n - 1) if not S >> k & 1]
if fuera:
cand = (dp[S][:, None] + Dm[:, fuera]).min(axis=0)
for k, val in zip(fuera, cand):
dp[S | 1 << k, k] = min(dp[S | 1 << k, k], val)
return float((dp[N - 1] + D[1:, 0]).min())
rng = np.random.default_rng(2)
F = []
for _ in range(20):
D = distancias(rng.random((9, 2)))
opt = held_karp(D)
c, wT, wM = christofides(D)
F.append((longitud(arbol_doblado(D), D) / opt, longitud(c, D) / opt, wT / opt, wM / opt))
F = np.array(F)
print("20 instancias de 9 ciudades en el cuadrado unidad:")
for nombre, col in [("árbol doblado / OPT", 0), ("Christofides / OPT", 1), ("w(T) / OPT", 2), ("w(M) / OPT", 3)]:
print(f" {nombre:20s} media {F[:, col].mean():.3f}, máximo {F[:, col].max():.3f}")
ref = nx.approximation.christofides(nx.from_numpy_array(D))
print("networkx.approximation.christofides en la última instancia:", round(longitud(ref[:-1], D) / opt, 3),
" la nuestra:", round(F[-1, 1], 3))
for n in [8, 12, 16]: # sin desigualdad triangular: distancia al cuadrado entre puntos de una recta
x = np.arange(n, dtype=float)
D2 = (x[:, None] - x[None, :]) ** 2
print(f"{n} puntos en una recta con d = distancia²: árbol doblado / OPT = {longitud(arbol_doblado(D2), D2) / held_karp(D2):.2f}")The analysis inequalities hold with room to spare: is around 70 % of optimum and less than half, so their sum is already usually above optimum, and shortcuts reduce the final ratio to a few percentage points. The doubled tree loses considerably more on average. The networkx implementation (same idea, its own tree and matching) matches ours on the last instance. With squared distances on a line the doubled tree exceeds 2 at 8 points and grows with : the minimum tree is the line (weight-1 edges), preorder from an endpoint traverses it and returns with a jump of weight , and no theorem forbids it because the metric assumption is false.
import itertools
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
def gonzalez(D, k, primero=0):
centros, dist = [primero], D[primero].copy()
while len(centros) < k:
c = int(np.argmax(dist)) # el punto peor atendido pasa a ser centro
centros.append(c)
dist = np.minimum(dist, D[c])
return centros, dist.max()
def kcentro_exacto(D, k):
"""Centros entre los propios puntos, enumerando los C(n, k) subconjuntos."""
return min(D[list(C)].min(axis=0).max() for C in itertools.combinations(range(len(D)), k))
rng = np.random.default_rng(3)
cocientes = []
for _ in range(15):
P = rng.random((16, 2))
D = np.sqrt(((P[:, None] - P[None]) ** 2).sum(-1))
for k in (2, 3, 4):
_, r = gonzalez(D, k, primero=int(rng.integers(16)))
cocientes.append(r / kcentro_exacto(D, k))
print(f"k-centro, 45 casos (16 puntos, k = 2, 3, 4): Gonzalez / OPT media {np.mean(cocientes):.3f}, máximo {np.max(cocientes):.3f}")
def lista(p, m):
carga = np.zeros(m)
for t in p:
carga[np.argmin(carga)] += t
return carga.max()
def lpt(p, m):
return lista(sorted(p, reverse=True), m)
def makespan_exacto(p, m):
"""MILP: x[j, i] = 1 si el trabajo j va a la máquina i; C >= carga de cada máquina; minimizar C."""
n = len(p)
c = np.r_[np.zeros(n * m), 1.0]
A1 = np.zeros((n, n * m + 1))
for j in range(n):
A1[j, j * m:(j + 1) * m] = 1
A2 = np.zeros((m, n * m + 1))
for i in range(m):
A2[i, i:n * m:m] = p
A2[i, -1] = -1
r = milp(c, constraints=[LinearConstraint(A1, 1, 1), LinearConstraint(A2, -np.inf, 0)],
integrality=np.r_[np.ones(n * m), 0], bounds=Bounds(0, np.r_[np.ones(n * m), np.inf]))
return r.fun
F = []
for _ in range(20):
m = int(rng.integers(2, 5))
p = rng.integers(1, 21, size=10).astype(float)
opt = makespan_exacto(p, m)
F.append((lista(p, m) / opt, lpt(p, m) / opt, max(p.sum() / m, p.max()) / opt))
F = np.array(F)
print("planificación, 20 casos (10 trabajos, m de 2 a 4):")
print(f" lista / OPT: media {F[:, 0].mean():.3f}, máximo {F[:, 0].max():.3f}")
print(f" LPT / OPT: media {F[:, 1].mean():.3f}, máximo {F[:, 1].max():.3f}")
print(f" cota max(suma/m, p_max) / OPT: media {F[:, 2].mean():.3f}, mínimo {F[:, 2].min():.3f}")
for m in (3, 5):
p = [m] * 3 + [s for s in range(m + 1, 2 * m) for _ in range(2)]
print(f"instancia ajustada para LPT, m = {m}: LPT {lpt(p, m):.0f}, OPT {makespan_exacto(np.array(p, float), m):.0f}, "
f"cociente {lpt(p, m) / makespan_exacto(np.array(p, float), m):.4f}, cota {4 / 3 - 1 / (3 * m):.4f}")Gonzalez comes closest to its guarantee in practice: mean and one case , because farthest-first traversal does not try to balance anything. List scheduling loses 12 % on average (33 % worst case), far from but clearly above LPT, which loses 2 % on average and under 10 % in the worst case. The last line shows why both analyses work well here: bound is within 4 % of optimum in every case. Tight instances reach exactly .
Lab: minimum test selection
Now an applied case with library tools. A project has 400 functions in 20 modules of 20 and a test suite with three profiles generated by an explicit model: 220 unit tests exercising 3 to 8 functions from one module, taking 0.2 to 1 s; 60 integration tests exercising 5 to 12 functions from each of two modules, taking 2 to 8 s; and 12 end-to-end tests touching 8 modules, taking 30 to 90 s. Add one unit test for each function exercised by no test. Seek two things: the smallest number of tests exercising all functions, and the smallest CI time. Both are set covers.
import time
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
from scipy.sparse import csr_matrix
rng = np.random.default_rng(7)
MODULOS, POR_MODULO = 20, 20
F = MODULOS * POR_MODULO
def del_modulo(mod, k):
return set((mod * POR_MODULO + rng.choice(POR_MODULO, size=k, replace=False)).tolist())
tests, coste, tipo = [], [], []
for _ in range(220):
tests.append(del_modulo(rng.integers(MODULOS), rng.integers(3, 9))); coste.append(rng.uniform(0.2, 1.0)); tipo.append("unitario")
for _ in range(60):
a, b = rng.choice(MODULOS, 2, replace=False)
tests.append(del_modulo(a, rng.integers(5, 13)) | del_modulo(b, rng.integers(5, 13))); coste.append(rng.uniform(2, 8)); tipo.append("integración")
for _ in range(12):
tests.append(set().union(*(del_modulo(md, rng.integers(4, 10)) for md in rng.choice(MODULOS, 8, replace=False))))
coste.append(rng.uniform(30, 90)); tipo.append("e2e")
for f in sorted(set(range(F)) - set().union(*tests)):
tests.append({f}); coste.append(rng.uniform(0.2, 1.0)); tipo.append("unitario")
coste = np.array(coste)
m = len(tests)
filas, cols = zip(*[(f, j) for j, S in enumerate(tests) for f in S])
A = csr_matrix((np.ones(len(filas)), (filas, cols)), shape=(F, m))
print(f"{F} funciones, {m} tests; cada función la ejecutan entre {A.sum(1).min():.0f} y {A.sum(1).max():.0f} tests")
print(f"ejecutar la suite entera: {coste.sum():.0f} s")
def voraz(c):
sin, elegidos = set(range(F)), []
while sin:
j = min((j for j in range(m) if tests[j] & sin), key=lambda j: c[j] / len(tests[j] & sin))
sin -= tests[j]; elegidos.append(j)
return elegidos
def podar(elegidos, c):
"""Quita, del más caro al más barato, cada test cuyas funciones ya ejecutan los demás elegidos."""
cuenta = np.asarray(A[:, elegidos].sum(axis=1)).ravel()
sel = set(elegidos)
for j in sorted(elegidos, key=lambda j: -c[j]):
idx = list(tests[j])
if (cuenta[idx] >= 2).all():
cuenta[idx] -= 1; sel.discard(j)
return sorted(sel)
def resolver(c, nombre):
t = time.perf_counter(); G = voraz(c); tg = time.perf_counter() - t
t = time.perf_counter(); lp = linprog(c, A_ub=-A, b_ub=-np.ones(F), bounds=(0, 1), method="highs"); tl = time.perf_counter() - t
rondas = int(np.ceil(np.log(4 * F)))
while True:
elegido = np.zeros(m, dtype=bool)
for _ in range(rondas):
elegido |= rng.random(m) < lp.x
if (A[:, np.flatnonzero(elegido)].sum(axis=1) > 0).all():
break
R = list(np.flatnonzero(elegido))
t = time.perf_counter()
ex = milp(c, constraints=LinearConstraint(A, lb=1), integrality=np.ones(m), bounds=Bounds(0, 1))
te = time.perf_counter() - t
opt = ex.fun
print(f"\n{nombre}: LP* = {lp.fun:.2f}, OPT = {opt:.2f}, OPT / LP* = {opt / lp.fun:.3f}")
for etiqueta, sol in [("voraz", G), ("voraz + poda", podar(G, c)), ("redondeo aleatorizado", R), ("redondeo + poda", podar(R, c))]:
print(f" {etiqueta:22s} {c[sol].sum():8.2f} ({c[sol].sum() / opt:.3f} OPT, {len(sol)} tests)")
print(f" tiempos: voraz {1000 * tg:.0f} ms, LP {1000 * tl:.0f} ms, MILP {1000 * te:.0f} ms")
return ex
resolver(np.ones(m), "mínimo número de tests")
ex = resolver(coste, "mínimo tiempo de CI (s)")
sel = np.flatnonzero(ex.x > 0.5)
print("\nselección óptima por tiempo, por tipo:", {t: int(sum(tipo[j] == t for j in sel)) for t in ("unitario", "integración", "e2e")})What comes out, and why:
- The relaxation is almost exact. is within 1.4 % in test count and 0.2 % in time. With a lower bound this close to optimum, the solver’s branch and bound discards almost every branch, and HiGHS proves optimality in a fraction of a second. Do not generalize: families with gap exist and relaxation does not do that work there.
- Greedy is good, and better with pruning. It loses 8 % in test count and 11 % in time, mainly because it initially chooses some slow test covering many functions that later becomes redundant. Pruning redundant tests, which does not alter the guarantee, brings it within 1 % of optimum.
- Randomized rounding alone is bad; with pruning, competitive. Its 8 rounds include almost every set with , explaining the high test-count ratio. Pruned, it matches or beats pruned greedy.
- The time-optimal selection has 78 unit tests, 5 integration and 3 end-to-end: a few slow tests pay off when they exercise many functions otherwise requiring many separate unit tests. It goes from 1194 s to 269 s CI.
Times printed by the cell vary by machine and run; the robust fact is the order of magnitude: all three methods finish in a fraction of a second with 400 functions. The practical lesson echoes optimization manuals: if the integer solver solves your instance, use it; an approximation algorithm helps when it cannot (millions of elements, streaming decisions, no commercial solver license) and, above all, tells you in any case how much you may be losing.
Typical mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. How many elements does have at least?
Step 1 of 3. How do you relate to ?
Step 1 of 3. What traveling-salesperson instance do you construct?
lpt(p, m): it receives a list p of positive durations and a number of machines m, and returns (makespan, asignacion), where asignacion[j] is the machine (0 to m-1) of job j in the original order of p. Sort jobs largest first and assign each to the least-loaded machine, using a heap (heapq) for cost . Tests check the assignment is valid, the makespan agrees with it, it reaches bound on the tight instance, and never exceeds it against exact optimum on small instances.import heapq
def lpt(p, m):
"""Devuelve (makespan, asignacion) del algoritmo LPT con m máquinas."""
asignacion = [0] * len(p) # tu código: ordenar por duración y usar un montículo de (carga, máquina)
makespan = sum(p)
return makespan, asignacionSummary
- The approximation ratio is a multiplicative worst-case guarantee valid for every instance; it says little about typical behavior, which must be measured.
- Vertex cover: endpoints of a maximal matching and rounding the linear relaxation at give factor 2. The integrality gap, in , prevents going below 2 with that relaxation, and under the unique games conjecture nobody can.
- Set cover: greedy by cost per new element is an -approximation (prices and averaging; with dual fitting, versus ), and is NP-hard. Randomized rounding gives using Markov and the union bound and generalizes to many more problems.
- Traveling salesperson: without the triangle inequality no constant factor exists unless P = NP; with it the doubled tree gives 2 and Christofides , because the matching of odd vertices weighs at most half optimum.
- k-center: Gonzalez farthest-first gives 2 by a packing argument, and is NP-hard. k-means++ is its randomized version for another objective.
- Scheduling: Graham list scheduling gives even online; LPT gives , and both bounds are tight.
- In practice compute : it certifies how much you may be losing and, if the relaxation is tight, an integer solver may give the optimum directly.