TExcelTAD

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 O(n22n)O(n^2 2^n), SAT solvers, integer programming; vertex cover in O(2kn)O(2^k n)
optimality approximation algorithms with a proven ratio vertex cover within 2, metric TSP within 2 (Christofides: 3/2), knapsack within 1+ϵ1 + \epsilon
guarantees altogether heuristics local search (2-opt for TSP), simulated annealing, genetic algorithms

An algorithm for a minimization problem is a ρ\rho-approximation if it runs in polynomial time and always returns a solution of cost at most ρ\rho 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

text
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 C

Theorem. APPROX-VERTEX-COVER returns a vertex cover at most twice the size of a minimum one.

Proof. Every edge removed in line 6 touches CC, so CC is a cover. The edges picked in line 4 share no endpoints (after picking (u,v)(u, v) all edges at uu and vv are gone), so they form a matching MM, and ∣C∣=2∣M∣\lvert C \rvert = 2\lvert M \rvert. Any vertex cover, in particular an optimal one C∗C^*, must contain an endpoint of each edge of MM, and these endpoints are distinct because MM is a matching. So ∣C∗∣≥∣M∣\lvert C^* \rvert \ge \lvert M \rvert and ∣C∣=2∣M∣≤2∣C∗∣\lvert C \rvert = 2\lvert M \rvert \le 2\lvert C^* \rvert.

The matching is the lower bound. The program compares the approximation with the exact optimum (brute force) on random graphs.

python · try it yourself
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 nn disjoint edges the algorithm takes all 2n2n vertices while nn 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 c(u,w)≤c(u,v)+c(v,w)c(u, w) \le c(u, v) + c(v, w): going directly is never longer than a detour. For such metric costs:

text
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 r

Theorem. For metric costs, APPROX-TSP-TOUR returns a tour of cost at most twice the optimum.

Proof. Deleting one edge of an optimal tour H∗H^* leaves a spanning tree, so the MST costs c(T)≤c(H∗)c(T) \le c(H^*): the lower bound. A full walk of TT, going down and back up every tree edge, costs exactly 2c(T)2c(T). 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 2c(T)≤2c(H∗)2c(T) \le 2c(H^*).

Christofides' algorithm (1976) improves the factor to 3/23/2 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.

python · try it yourself
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, MST≤optimum≤MST tour≤2⋅MST\text{MST} \le \text{optimum} \le \text{MST tour} \le 2 \cdot \text{MST}, 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 kk: any edge (u,v)(u, v) forces uu or vv into the cover, so branch on the two choices, each time deleting the chosen vertex and lowering kk. The search tree has depth at most kk and at most 2k2^k leaves, so the running time is O(2k(V+E))O(2^k (V + E)): polynomial for every fixed kk, and practical for kk 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.

cpp · try it yourself
#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?

  1. The number of vertices
  2. The size of the matching formed by the picked edges
  3. The maximum degree
  4. The number of edges divided by 2

Why does the MST-based tour need the triangle inequality?

  1. To compute the MST
  2. So that skipping already visited vertices (shortcutting) never makes the walk longer
  3. To make the graph complete
  4. It does not need it

Why is the cost of a minimum spanning tree at most the cost of an optimal tour?

  1. Because a tour minus one edge is a spanning tree
  2. Because MSTs are unique
  3. Because tours have n−1n - 1 edges
  4. By the triangle inequality

What is the running time of the branching algorithm for vertex cover with parameter kk?

  1. O(nk)O(n^k)
  2. O(2k(V+E))O(2^k (V + E))
  3. O(2V)O(2^V)
  4. O(k2)O(k^2)