Coping with NP-Hardness
An NP-hardness proof says that, unless P = NP, no algorithm is correct, fast and general at once. Real problems still have to be solved, so practitioners give up one of the three on purpose. This closing lesson of the section surveys the main options and works out two of them in detail: a 2-approximation for vertex cover from a maximal matching, and a 2-approximation for metric TSP from a minimum spanning tree. Both are the opening examples of the Part II course Approximation Algorithms.
Four ways out
| Give up | Approach | Examples |
|---|---|---|
| generality | solve special cases exactly | vertex cover on trees or bipartite graphs (by matching), TSP on points in a line, 2-SAT, knapsack with small numbers |
| speed in the worst case | exact exponential algorithms that are fast in practice or for small parameters | backtracking, branch and bound, Held-Karp in , SAT solvers, integer programming; vertex cover in |
| optimality | approximation algorithms with a proven ratio | vertex cover within 2, metric TSP within 2 (Christofides: 3/2), knapsack within |
| guarantees altogether | heuristics | local search (2-opt for TSP), simulated annealing, genetic algorithms |
An algorithm for a minimization problem is a -approximation if it runs in polynomial time and always returns a solution of cost at most times the optimum. The challenge in proving such a ratio is that the optimum is unknown; every proof compares the algorithm's cost with a lower bound on the optimum that can be computed.
Vertex cover: a 2-approximation
APPROX-VERTEX-COVER(G)
1 C = empty set
2 E' = the edges of G
3 while E' is not empty
4 pick any edge (u, v) in E'
5 add both u and v to C
6 remove from E' every edge touching u or v
7 return CTheorem. APPROX-VERTEX-COVER returns a vertex cover at most twice the size of a minimum one.
Proof. Every edge removed in line 6 touches , so is a cover. The edges picked in line 4 share no endpoints (after picking all edges at and are gone), so they form a matching , and . Any vertex cover, in particular an optimal one , must contain an endpoint of each edge of , and these endpoints are distinct because is a matching. So and .
The matching is the lower bound. The program compares the approximation with the exact optimum (brute force) on random graphs.
import random
from itertools import combinations
def approx_vertex_cover(edges):
cover, remaining = set(), list(edges)
while remaining:
u, v = remaining[0]
cover |= {u, v}
remaining = [e for e in remaining if u not in e and v not in e]
return cover
def min_vertex_cover(n, edges):
for k in range(n + 1):
for C in combinations(range(n), k):
if all(u in C or v in C for u, v in edges):
return set(C)
rng = random.Random(17)
worst = 0
print(" n edges approx optimum ratio")
for trial in range(8):
n = rng.randint(6, 11)
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.3]
a, o = approx_vertex_cover(edges), min_vertex_cover(n, edges)
ratio = len(a) / max(1, len(o))
worst = max(worst, ratio)
print(f"{n:2} {len(edges):6} {len(a):7} {len(o):8} {ratio:6.2f}")
print("worst ratio seen:", round(worst, 2), "(guaranteed at most 2)") n edges approx optimum ratio
10 9 8 5 1.60
6 4 4 3 1.33
8 9 4 3 1.33
6 4 4 2 2.00
7 5 4 3 1.33
6 1 2 1 2.00
10 14 6 5 1.20
8 7 6 4 1.50
worst ratio seen: 2.0 (guaranteed at most 2)
The ratio 2 can be attained: on a perfect matching of disjoint edges the algorithm takes all vertices while suffice. Improving the constant 2 by any fixed amount is a famous open problem; under the Unique Games Conjecture it is impossible.
Metric TSP: a 2-approximation
General TSP has no constant-factor approximation unless P = NP (Hamiltonian Cycles and the Travelling Salesman). But real distances usually satisfy the triangle inequality : going directly is never longer than a detour. For such metric costs:
APPROX-TSP-TOUR(G, c)
1 T = a minimum spanning tree of G, rooted at any vertex r // Prim or Kruskal
2 L = the vertices of T in preorder (a depth-first walk, first visits only)
3 return the tour L followed by rTheorem. For metric costs, APPROX-TSP-TOUR returns a tour of cost at most twice the optimum.
Proof. Deleting one edge of an optimal tour leaves a spanning tree, so the MST costs : the lower bound. A full walk of , going down and back up every tree edge, costs exactly . The preorder tour visits the vertices in the same order as the full walk but skips repeated vertices; by the triangle inequality each shortcut is no longer than the part of the walk it replaces. So the tour costs at most .
Christofides' algorithm (1976) improves the factor to by adding a minimum-weight perfect matching on the odd-degree vertices of the tree instead of doubling it. The program runs the MST tour on random points with Euclidean distances, a metric, and compares it with the exact optimum from Held-Karp.
import random
from math import dist, inf
def mst_tour(pts):
n = len(pts)
in_tree, parent, best = [False] * n, [0] * n, [inf] * n
best[0], children = 0, {i: [] for i in range(n)}
for _ in range(n): # Prim, O(n^2)
u = min((i for i in range(n) if not in_tree[i]), key=lambda i: best[i])
in_tree[u] = True
if u:
children[parent[u]].append(u)
for v in range(n):
if not in_tree[v] and dist(pts[u], pts[v]) < best[v]:
best[v], parent[v] = dist(pts[u], pts[v]), u
mst = sum(dist(pts[v], pts[parent[v]]) for v in range(1, n))
order, stack = [], [0]
while stack: # preorder walk
u = stack.pop()
order.append(u)
stack.extend(reversed(children[u]))
tour = sum(dist(pts[order[i]], pts[order[(i + 1) % n]]) for i in range(n))
return tour, mst
def held_karp(pts):
n = len(pts)
D = {(1, 0): 0.0}
for S in range(1, 1 << n, 2):
for j in range(n):
if (S, j) not in D:
continue
for k in range(1, n):
if not S >> k & 1:
key, val = (S | 1 << k, k), D[(S, j)] + dist(pts[j], pts[k])
if val < D.get(key, inf):
D[key] = val
full = (1 << n) - 1
return min(D[(full, j)] + dist(pts[j], pts[0]) for j in range(1, n))
rng = random.Random(4)
print(" n MST MST tour optimum tour / optimum")
for n in [6, 8, 10]:
pts = [(rng.randint(0, 100), rng.randint(0, 100)) for _ in range(n)]
tour, mst = mst_tour(pts)
opt = held_karp(pts)
print(f"{n:2} {mst:7.1f} {tour:9.1f} {opt:9.1f} {tour / opt:12.3f}") n MST MST tour optimum tour / optimum
6 126.8 225.4 217.0 1.039
8 208.7 321.7 299.3 1.075
10 177.9 299.7 255.9 1.171
In each row, , and in practice the MST tour is usually much closer to the optimum than the factor 2 suggests; a few rounds of 2-opt local search typically bring it within a few percent.
Exact, but exponential only in a parameter
Some NP-hard problems are hard only because of one parameter. Vertex cover with a size bound : any edge forces or into the cover, so branch on the two choices, each time deleting the chosen vertex and lowering . The search tree has depth at most and at most leaves, so the running time is : polynomial for every fixed , and practical for in the dozens even on large graphs. Such fixed-parameter tractable algorithms are the subject of Parameterized & Fine-Grained Complexity.
In C++
The metric TSP approximation in C++: Prim's algorithm on a complete graph of 200 points, a preorder walk, and the three numbers of the proof.
#include <cmath>
#include <cstdio>
#include <vector>
int main() {
const int n = 200;
std::vector<double> x(n), y(n);
unsigned s = 2024;
for (int i = 0; i < n; i++) {
s = s * 1103515245u + 12345u; x[i] = (s >> 16) % 1000;
s = s * 1103515245u + 12345u; y[i] = (s >> 16) % 1000;
}
auto d = [&](int a, int b) { return std::hypot(x[a] - x[b], y[a] - y[b]); };
std::vector<bool> in(n, false);
std::vector<double> best(n, 1e18);
std::vector<int> parent(n, 0);
std::vector<std::vector<int>> kids(n);
best[0] = 0;
double mst = 0;
for (int it = 0; it < n; it++) {
int u = -1;
for (int i = 0; i < n; i++) if (!in[i] && (u < 0 || best[i] < best[u])) u = i;
in[u] = true; mst += best[u];
if (u) kids[parent[u]].push_back(u);
for (int v = 0; v < n; v++) if (!in[v] && d(u, v) < best[v]) { best[v] = d(u, v); parent[v] = u; }
}
std::vector<int> order, stack = {0};
while (!stack.empty()) {
int u = stack.back(); stack.pop_back();
order.push_back(u);
for (int i = int(kids[u].size()) - 1; i >= 0; i--) stack.push_back(kids[u][i]);
}
double tour = 0;
for (int i = 0; i < n; i++) tour += d(order[i], order[(i + 1) % n]);
std::printf("MST %.1f, tour %.1f, tour / MST = %.3f (at most 2; optimum is between them)\n", mst, tour, tour / mst);
}MST 9489.9, tour 14616.1, tour / MST = 1.540 (at most 2; optimum is between them)
Test yourself
What lower bound on the optimum does the analysis of APPROX-VERTEX-COVER use?
- The number of vertices
- The size of the matching formed by the picked edges
- The maximum degree
- The number of edges divided by 2
Why does the MST-based tour need the triangle inequality?
- To compute the MST
- So that skipping already visited vertices (shortcutting) never makes the walk longer
- To make the graph complete
- It does not need it
Why is the cost of a minimum spanning tree at most the cost of an optimal tour?
- Because a tour minus one edge is a spanning tree
- Because MSTs are unique
- Because tours have edges
- By the triangle inequality
What is the running time of the branching algorithm for vertex cover with parameter ?