---
title: "Approximation and Exact Methods for Hard Problems"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 18
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/18-approximation-and-exact-methods-for-hard-problems
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 18 — Approximation and Exact Methods for Hard Problems

[Chapter 17](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#ch-b3-np-completeness) showed that vertex cover, the travelling salesman problem and satisfiability are [NP-complete](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-reduction): no algorithm is known that solves every instance in polynomial time. Yet delivery vans get routed and chips get verified every day. This chapter is about how. There are two ways out. An [approximation algorithm](#def-b3-hard-problems-approximation) runs in polynomial time and proves how far from the optimum it can be. An exact method searches, but prunes so much that real instances finish: branch and bound with a relaxation, and the clause-learning solvers that decide formulas with millions of clauses. Between them sit Horn formulas, a special case that is easy, and [local search](#def-b3-hard-problems-local-search), which is often good and promises nothing. Every method is run against the exact optimum on small instances, and the gaps are measured.

**You already know.**

A matching of a graph is a set of edges no two of which share a vertex (Year 2 volume). A minimum spanning tree connects all the vertices of a weighted graph with the least total weight, and Prim’s algorithm finds one (Year 1 volume). Branch and bound explores a tree of partial choices and cuts a branch as soon as a bound shows it cannot beat the best solution found so far; backtracking undoes the last choice when it fails (Year 1 volume). Unit propagation sets the last literal of a clause whose other literals are all false (Year 1 volume). The DPLL solver `dpll.py` of [Chapter 17](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#ch-b3-np-completeness) propagates units, then branches on a variable.

## 18.1 Approximation ratios

**Definition 18.1 (Approximation algorithm, approximation ratio, maximal matching).**

For a minimisation problem, an *approximation algorithm* with *approximation ratio* $\rho \ge 1$ runs in polynomial time and returns, on every instance, a solution of cost at most $\rho$ times the optimum. A *maximal matching* is a matching to which no edge can be added; it need not be a matching of largest size.

The ratio is a promise about the worst instance, proved against an optimum the algorithm never sees. The proof always goes through a lower bound on the optimum that is easy to compute.

**Theorem 18.2 (Vertex cover by matching).**

Taking both ends of every edge of a [maximal matching](#def-b3-hard-problems-approximation) gives a vertex cover at most twice the smallest, and the factor 2 is reached.

The cover covers every edge, since an uncovered edge could be added to the matching. And any cover must contain one end of each matched edge, which share no vertex: the smallest cover has at least as many vertices as the matching has edges, half of what the algorithm takes. [Exercise 18.7](#exo-b3-hard-problems-7) completes the proof; the figure after the output shows a tight case.

```python
def matching_cover(edges):
    cover = set()
    for u, v in edges:  # an edge with no end covered yet joins the matching
        if u not in cover and v not in cover:
            cover |= {u, v}
    return cover
```

***Listing 18.1.** Vertex cover from a [maximal matching](#def-b3-hard-problems-approximation) built greedily, edge by edge. code/bachelor-3/18-hard-problems/listings/vertex_cover.py*

```
$ python vertex_cover.py
 n   edges   matching cover   minimum   ratio
 8      10                6         4   1.50
10      12                8         5   1.60
12      16               10         6   1.67
14      36               12         9   1.33
5 disjoint edges: matching cover 10, minimum 5
```

***Output 18.1.** Against the exact minimum on four random graphs, and on disjoint edges, where the factor 2 is reached.*

![A tight case of : in the complete bipartite graph on 3 + 3 vertices the matching may be perfect, and the algorithm takes 6 vertices where 3 suffice.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-hard-problems/fig-abd570b684f9.svg)

*A tight case of [Theorem 18.2](#thm-b3-hard-problems-vertex-cover): in the complete bipartite graph on $3 + 3$ vertices the matching may be perfect, and the algorithm takes 6 vertices where 3 suffice.*

### 18.1.1 Set cover

**Definition 18.3 (Set cover problem).**

The *set cover problem*: given a universe $U$ of $n$ elements and sets $S_1, \ldots, S_k$ whose union is $U$, choose as few sets as possible whose union is $U$.

Vertex cover is the special case where the elements are edges and each set is the edges at one vertex. The greedy algorithm takes, again and again, the set covering most of what is still uncovered.

```python
def greedy(universe, sets):
    uncovered, chosen = set(universe), []
    while uncovered:
        i = max(range(len(sets)), key=lambda i: len(sets[i] & uncovered))
        chosen.append(i)
        uncovered -= sets[i]
    return chosen
```

***Listing 18.2.** Greedy set cover. code/bachelor-3/18-hard-problems/listings/set_cover.py*

**Theorem 18.4 (Greedy set cover).**

The greedy algorithm returns a cover at most $H(n) = 1 + \frac{1}{2} + \cdots + \frac{1}{n}$ times the smallest, and $H(n) \le \ln n + 1$.

The bound is due to David Johnson in 1974 and László Lovász in 1975; [Exercise 18.10](#exo-b3-hard-problems-10) proves it by charging each element a share of the set that covers it first.

```
$ python set_cover.py
greedy: [2, 3, 4]  exact: [0, 1]
68 random instances: mean ratio 1.048, worst 1.400
```

***Output 18.2.** An instance built to fool greedy, which takes the largest set first and needs 3 where 2 suffice; and random instances, where greedy is usually optimal.*

### 18.1.2 The travelling salesman

**Definition 18.5 (Metric travelling salesman problem, tree doubling).**

The *metric travelling salesman problem* asks for a shortest tour through $n$ points whose distances satisfy the triangle inequality $d(a, c) \le d(a, b) + d(b, c)$. *Tree doubling* walks round a minimum spanning tree, going down and up each edge once, and skips every point already visited.

**Theorem 18.6 (Tree doubling).**

On metric instances, [tree doubling](#def-b3-hard-problems-tsp) returns a tour at most twice the shortest.

**Proof.** Removing one edge from a shortest tour leaves a spanning tree, so the minimum spanning tree weighs at most the optimum $T^*$. The walk round the tree crosses every edge twice, a closed walk of length $2\,\mathrm{MST} \le 2T^*$ through every point. Skipping a visited point replaces two steps $a \to b \to c$ by $a \to c$, which is no longer by the triangle inequality. So the tour is at most $2T^*$. ∎

Walking round the tree and skipping repeats visits the points in preorder, which is what `tree_doubling` computes. Nicos Christofides published in 1976 a refinement within $3/2$ of the optimum, which adds a minimum matching on the odd-degree vertices of the tree instead of doubling it; Anatoliy Serdyukov found it independently. It is told here, not built. The exact answer for a few places comes from the Held–Karp dynamic program of 1962: for each set $S$ of places and each $j \in S$, the shortest path from place 0 through all of $S$ ending at $j$.

```python
def held_karp(points):
    """Exact: best[(S, j)] = shortest path from 0 through the set S, ending at j."""
    n = len(points)
    d = [[dist(p, q) for q in points] for p in points]
    best = {(1 << j, j): (d[0][j], 0) for j in range(1, n)}
    for size in range(2, n):
        for s in range(1 << n):
            if s & 1 or bin(s).count("1") != size:
                continue
            for j in range(1, n):
                if s >> j & 1:
                    rest = s & ~(1 << j)
                    best[(s, j)] = min((best[(rest, k)][0] + d[k][j], k)
                                       for k in range(1, n) if rest >> k & 1)
    full = (1 << n) - 2
    _, j = min((best[(full, j)][0] + d[j][0], j) for j in range(1, n))
    tour, s = [], full
    while j:
        tour.append(j)
        s, j = s & ~(1 << j), best[(s, j)][1]
    return [0] + tour[::-1]
```

***Listing 18.3.** Held–Karp: exact, in time about $n^2 2^n$. code/bachelor-3/18-hard-problems/listings/tsp.py*

```python
def tree_doubling(points):
    """Walk round the minimum spanning tree, skipping the vertices already visited:
    the preorder of the tree."""
    children, tour, stack = minimum_spanning_tree(points), [], [0]
    while stack:
        v = stack.pop()
        tour.append(v)
        stack.extend(reversed(children[v]))
    return tour
```

***Listing 18.4.** [Tree doubling](#def-b3-hard-problems-tsp): the preorder of the minimum spanning tree. code/bachelor-3/18-hard-problems/listings/tsp.py*

The delivery van of Brenmoor serves 12 of the town’s places, with straight-line distances between them.

![The van’s 12 places. Left: the minimum spanning tree (grey, 11,367 m) and the tour tree doubling takes from it (18,427 m). Right: the optimal tour (16,635 m), from Held–Karp.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-hard-problems/fig-e19ac006b53c.svg)

*The van’s 12 places. Left: the minimum spanning tree (grey, 11,367 m) and the tour [tree doubling](#def-b3-hard-problems-tsp) takes from it (18,427 m). Right: the optimal tour (16,635 m), from Held–Karp.*

```
$ python tsp_demo.py
12 places: optimum 16,635 m
  tree doubling 18,427 m (ratio 1.108)
  then 2-opt    17,617 m (ratio 1.059)
200 instances, tree doubling: mean ratio 1.216, worst 1.456, optimal in 3
200 instances, then 2-opt   : mean ratio 1.022, worst 1.156, optimal in 103
```

***Output 18.3.** The van’s tour, then 200 seeded choices of 12 places out of 30: [tree doubling](#def-b3-hard-problems-tsp) stays well inside its factor 2, and 2-opt ([Section 18.5](#sec-18-5)) closes most of the gap.*

### 18.1.3 Problems with no good ratio

**Definition 18.7 (Inapproximability).**

A problem shows *inapproximability* at ratio $\rho$ when no polynomial-time algorithm achieves ratio $\rho$ unless $\mathrm{P} = \mathrm{NP}$.

Without the triangle inequality the travelling salesman has no constant ratio at all: an algorithm with ratio $\rho$ would decide whether a graph has a [Hamiltonian cycle](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-problems). Give the graph’s edges length 1 and every other pair length $\rho n + 1$. A [Hamiltonian cycle](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-problems) is a tour of length $n$; any other tour uses a non-edge and costs more than $\rho n$; so the algorithm’s tour has length at most $\rho n$ exactly when the graph has a [Hamiltonian cycle](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-problems) ([Exercise 18.11](#exo-b3-hard-problems-11)). Stronger results of this kind, showing that a constant ratio below some threshold is [NP-hard](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-reduction) even for problems that have one above it, come from the theory of probabilistically checkable proofs, which this book does not cover.

## 18.2 Branch and bound with a relaxation

**Definition 18.8 (Relaxed problem, relaxation bound).**

A *relaxed problem* drops or weakens a constraint, so that every solution of the original is still a solution and its optimum is at least as good. When it is easy to solve, its optimum is a *relaxation bound*: no solution of the original can beat it.

In the 0-1 knapsack problem each item is taken whole or left. Allowing fractions of items gives the fractional knapsack, solved by taking items in decreasing order of value per kilogram and cutting the first that does not fit: an item of higher value per kilogram can always replace an equal weight of a lower one without losing value, so the greedy filling is optimal for the [relaxed problem](#def-b3-hard-problems-relaxation). Its value bounds what the rest of the bag can still add. Linear programming relaxations, which drop the integrality of the variables of an integer program, are the general form, and are told here, not built.

```python
def fractional_bound(items, i, room, value):
    """The best value of the relaxed problem, where items may be cut."""
    for w, v in items[i:]:
        if w <= room:
            room, value = room - w, value + v
        else:
            return value + v * room / w
    return value


def branch_and_bound(items, capacity, use_bound):
    items = sorted(items, key=lambda it: it[1] / it[0], reverse=True)
    best, nodes = 0, 0

    def explore(i, room, value):
        nonlocal best, nodes
        nodes += 1
        best = max(best, value)
        if i == len(items):
            return
        if use_bound and fractional_bound(items, i, room, value) <= best:
            return  # prune: this branch cannot beat the best
        w, v = items[i]
        if w <= room:
            explore(i + 1, room - w, value + v)  # take item i
        explore(i + 1, room, value)  # leave it
    explore(0, capacity, 0)
    return best, nodes
```

***Listing 18.5.** Branch and bound for the 0-1 knapsack, with and without the fractional bound. code/bachelor-3/18-hard-problems/listings/knapsack_bb.py*

```
$ python knapsack_bb.py
 n   best value   nodes, no bound   nodes, fractional bound
10          229             1,365                        25
14          346            20,702                        69
18          466           321,858                        55
22          597         5,081,541                       162
```

***Output 18.4.** Nodes of the search tree on random instances, bag half the total weight. Without the bound the tree grows by about 16 for every four items; with it, it stays below two hundred.*

For the travelling salesman, a good relaxation of a tour is a *1-tree*: a spanning tree of all places but the first, plus the two shortest edges at the first. A tour is a 1-tree, so the cheapest 1-tree is a lower bound, 13,594 m for the van against an optimum of 16,635 m ([Exercise 18.6](#exo-b3-hard-problems-6)).

## 18.3 Satisfiability solvers that learn

`dpll.py` branches on a variable, propagates units, and on a contradiction backtracks to its last choice. Davis and Putnam published a resolution-based procedure in 1960; the branching procedure is from Davis, Logemann and Loveland, published in 1962.

Modern solvers keep the branching and add three ideas: cheap propagation, learning a clause from each contradiction, and jumping back further than one choice.

**Definition 18.9 (Watched literals, solver implication graph, conflict clause, clause learning, unique implication point, backjumping, CDCL solver).**

- *Watched literals* : each clause watches two of its literals that are not false; it is looked at only when one of them becomes false, to find another or to propagate.
- The *solver implication graph* has a vertex per assigned literal, labelled with its decision level, and an edge from each false literal of a clause to the literal that clause implied; a *conflict clause* has all its literals false.
- *Clause learning* adds to the formula a clause implied by it that rules out the cause of a conflict. A *unique implication point* is a literal of the current level through which every path from that level’s decision to the conflict passes; the first one is the nearest to the conflict.
- *Backjumping* undoes every assignment above a level that may be several levels below the current one.
- A *CDCL solver* (conflict-driven clause learning) combines the four.

Take the clauses $c_1 = \neg x_2 \vee x_3$, $c_2 = \neg x_1 \vee \neg x_3 \vee x_4$, $c_3 = \neg x_3 \vee x_5$, $c_4 = \neg x_4 \vee \neg x_5$, and decide $x_1$ at level 1, then $x_2$ at level 2. Propagation sets $x_3$, then $x_4$ and $x_5$, and $c_4$ is falsified. Resolving $c_4$ with the reason of $x_5$ gives $\neg x_4 \vee \neg x_3$; with the reason of $x_4$, $\neg x_1 \vee \neg x_3$. One literal of level 2 is left, $x_3$: the first [unique implication point](#def-b3-hard-problems-cdcl). The learned clause $\neg x_1 \vee \neg x_3$ says that $x_1$ and $x_3$ cannot both hold; the solver jumps back to level 1, where the clause is unit and sets $x_3$ false, without ever trying $x_2$ again.

![The solver implication graph of the example. Decisions are shaded; “@2” is the decision level. Every path from x_2 to the conflict passes through x_3. The literals with an edge across the cut, x_1 and x_3, give the learned clause x_1 x_3.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-hard-problems/fig-ff826b084877.svg)

*The [solver implication graph](#def-b3-hard-problems-cdcl) of the example. Decisions are shaded; “@2” is the decision level. Every path from $x_2$ to the conflict passes through $x_3$. The literals with an edge across the cut, $x_1$ and $x_3$, give the learned clause $\neg x_1 \vee \neg x_3$.*

`cdcl.py` implements this in about 140 lines. It decides the most active variable, the one met most often in recent conflicts, and tries it false first.

```python
    def propagate(self):
        """Unit propagation through the watches; returns a falsified clause or None."""
        while self.head < len(self.trail):
            falsified = -self.trail[self.head]
            self.head += 1
            watching = self.watches.get(falsified, [])
            self.watches[falsified] = []
            for k, ci in enumerate(watching):
                c = self.clauses[ci]
                if c[0] == falsified:
                    c[0], c[1] = c[1], c[0]
                if self.true(c[0]):
                    self.watches[falsified].append(ci)
                    continue
                for j in range(2, len(c)):  # look for another literal to watch
                    if not self.false(c[j]):
                        c[1], c[j] = c[j], c[1]
                        self.watches.setdefault(c[1], []).append(ci)
                        break
                else:
                    self.watches[falsified].append(ci)
                    if self.false(c[0]):  # every literal false: a conflict
                        self.watches[falsified] += watching[k + 1:]
                        return c
                    self.assign(c[0], ci)  # unit: c[0] is implied
        return None
```

***Listing 18.6.** Propagation with two [watched literals](#def-b3-hard-problems-cdcl): a clause is visited only when a watched literal becomes false. code/bachelor-3/18-hard-problems/listings/cdcl.py*

```python
    def analyse(self, conflict):
        """First UIP: resolve the conflict clause with the reasons of its literals of
        the current level, latest first, until one literal of that level is left."""
        level, seen, learned, count = self.decision_level(), set(), [], 0
        clause, i = conflict, len(self.trail) - 1
        while True:
            for lit in clause:
                v = abs(lit)
                if v in seen or self.level[v] == 0:
                    continue
                seen.add(v)
                self.activity[v] += 1
                if self.level[v] == level:
                    count += 1  # still to be resolved away
                else:
                    learned.append(lit)
            while abs(self.trail[i]) not in seen:
                i -= 1
            uip = self.trail[i]
            i, count = i - 1, count - 1
            if count == 0:
                break
            clause = [x for x in self.clauses[self.reason[abs(uip)]] if x != uip]
        learned.insert(0, -uip)  # the learned clause: not uip, or the earlier literals
        back = max((self.level[abs(x)] for x in learned[1:]), default=0)
        return learned, back
```

***Listing 18.7.** Conflict analysis to the first [unique implication point](#def-b3-hard-problems-cdcl). code/bachelor-3/18-hard-problems/listings/cdcl.py*

```python
    def solve(self):
        if self.unsat or self.propagate() is not None:
            return None, self.stats
        while True:
            conflict = self.propagate()
            if conflict is not None:
                self.stats["conflicts"] += 1
                if self.decision_level() == 0:
                    return None, self.stats
                learned, back = self.analyse(conflict)
                self.backjump(back)
                # watch the asserting literal and the latest of the others
                learned[1:] = sorted(learned[1:], key=lambda x: -self.level[abs(x)])
                ci = self.add(learned) if len(learned) > 1 else None
                self.assign(learned[0], ci)
                self.stats["learned"] += 1
                if self.restart_now() and self.limits:
                    self.backjump(0)  # keep the learned clauses, forget the decisions
                continue
            free = [v for v in range(1, self.n + 1) if v not in self.value]
            if not free:
                return dict(self.value), self.stats
            v = max(free, key=lambda v: (self.activity[v], -v))  # most active variable
            self.stats["decisions"] += 1
            self.limits.append(len(self.trail))
            self.assign(-v, None)  # try false first
```

***Listing 18.8.** The main loop: propagate, learn and backjump on a conflict, decide otherwise. code/bachelor-3/18-hard-problems/listings/cdcl.py*

The learned clause is asserting: after the backjump, all its literals but one are false, so propagation sets that one at once. Conflict-driven [clause learning](#def-b3-hard-problems-cdcl) was proposed by J. P. Marques-Silva and Karem Sakallah in 1996 and 1999, in the GRASP solver; the Chaff solver of 2001 engineered DPLL with such enhancements for speed.

Restarting the search from level 0 while keeping the learned clauses, now and then, is the last common ingredient ([Exercise 18.12](#exo-b3-hard-problems-12)).

The two solvers are compared below in decisions and conflicts, which do not depend on the machine. The pigeonhole formulas put $n + 1$ pigeons in $n$ holes, one hole each, and are unsatisfiable. Random 3-SAT formulas are taken at 4.26 clauses per variable, where Selman, Mitchell and Levesque, measuring the work of DPLL, found them passing from almost always satisfiable to almost always unsatisfiable (1996).

```python
def pigeonhole(n):
    """Variable p(i, j): pigeon i in hole j. Every pigeon somewhere, no hole shared."""
    def p(i, j):
        return i * n + j + 1
    clauses = [[p(i, j) for j in range(n)] for i in range(n + 1)]
    clauses += [[-p(i, j), -p(k, j)] for j in range(n)
                for i in range(n + 1) for k in range(i + 1, n + 1)]
    return clauses, (n + 1) * n
```

***Listing 18.9.** The pigeonhole formula. code/bachelor-3/18-hard-problems/listings/sat_compare.py*

```
$ python sat_compare.py
instance           answer   DPLL dec.  DPLL confl.   CDCL dec.  CDCL confl.
pigeonhole 5 in 4   UNSAT          23          24          39          29
pigeonhole 6 in 5   UNSAT         119         120         177         142
pigeonhole 7 in 6   UNSAT         719         720         668         532
pigeonhole 8 in 7   UNSAT       5,039       5,040       2,209       1,671
random n = 30       UNSAT          82          83          30          28
random n = 50         SAT          19           8          14           2
random n = 70       UNSAT         920         921         163         134
```

***Output 18.5.** Plain DPLL against CDCL. On pigeonhole formulas DPLL makes exactly $n! - 1$ decisions for $n$ holes.*

At small sizes the learning costs more than it saves; from 7 holes and on random formulas of 70 variables, CDCL makes 2 to 6 times fewer decisions, and the gap widens with the size. CDCL’s counts still grow fast on pigeonhole formulas: each learned clause is a step of a proof that the formula is unsatisfiable, and when every such proof is long, so is the search.

## 18.4 Horn clauses

**Definition 18.10 (Horn clause, Horn-SAT, forward chaining).**

A *Horn clause* has at most one positive literal: $\neg a_1 \vee \cdots \vee \neg a_k \vee b$ is the rule “if $a_1, \ldots, a_k$ then $b$”; with no positive literal it is a constraint, and with no negative one a fact. *Horn-SAT* is SAT for formulas of Horn clauses. *Forward chaining* applies the rules to the known facts until no new fact appears.

**Theorem 18.11 (Horn-SAT is in P).**

Set every variable false, then repeatedly make true the conclusion of a rule whose premises are all true. The formula is satisfiable if and only if no constraint ends with all its premises true, and then the resulting assignment satisfies it. With a counter per clause this takes time linear in the size of the formula.

**Proof.** Every variable made true is forced: by induction, it is true in every satisfying assignment. So if a constraint has all its premises true, no assignment satisfies the formula. Otherwise, when the process stops, a rule with all premises true has its conclusion true, a rule with a false premise is satisfied by it, and every constraint has a false premise. The time bound is [Exercise 18.8](#exo-b3-hard-problems-8). ∎

William Dowling and Jean Gallier published linear-time algorithms for Horn formulas in 1984. [Forward chaining](#def-b3-hard-problems-horn) is the same process on rules with variables. Brenmoor’s records list no families, so `horn.py` makes up parents for the town’s people, seeded, and derives grandparents and ancestors from three rules. Logic programming languages are built on [Horn clauses](#def-b3-hard-problems-horn) run this way, or backwards from a goal; they are told here, not built.

```python
def horn_sat(clauses, n):
    """Start with every variable false; a clause whose negative literals are all true
    forces its positive one. Each clause keeps a counter of negatives not yet true, so
    every literal is looked at a constant number of times."""
    waiting = [sum(1 for x in c if x < 0) for c in clauses]
    uses = {v: [] for v in range(1, n + 1)}
    for i, c in enumerate(clauses):
        for x in c:
            if x < 0:
                uses[-x].append(i)
    true, queue = set(), [i for i, w in enumerate(waiting) if w == 0]
    while queue:
        c = clauses[queue.pop()]
        head = [x for x in c if x > 0]
        if not head:
            return None  # every premise true, and no conclusion: unsatisfiable
        if head[0] in true:
            continue
        true.add(head[0])
        for i in uses[head[0]]:
            waiting[i] -= 1
            if waiting[i] == 0:
                queue.append(i)
    return {v: v in true for v in range(1, n + 1)}
```

***Listing 18.10.** [Horn-SAT](#def-b3-hard-problems-horn): a counter of premises still false per clause, and a queue of clauses ready to fire. code/bachelor-3/18-hard-problems/listings/horn.py*

```python
RULES = [  # (premises, conclusion); capital letters are variables
    ([("parent", "X", "Y")], ("ancestor", "X", "Y")),
    ([("parent", "X", "Y"), ("ancestor", "Y", "Z")], ("ancestor", "X", "Z")),
    ([("parent", "X", "Y"), ("parent", "Y", "Z")], ("grandparent", "X", "Z")),
]
```

***Listing 18.11.** Three rules; capital letters are variables. code/bachelor-3/18-hard-problems/listings/horn.py*

```
$ python horn.py
Horn-SAT: {1: True, 2: True, 3: True, 4: True, 5: False}
with [5] added: None
parent       facts:   190
grandparent  facts:   158
ancestor     facts:   360
rounds until nothing new: 4
for example: Nils is a grandparent of Leo
```

***Output 18.6.** A Horn formula and the assignment found, the smallest that satisfies it; adding the fact $x_5$ violates the constraint $\neg x_4 \vee \neg x_5$. Then [forward chaining](#def-b3-hard-problems-horn) on 190 generated parent facts.*

Ancestors take three rounds that add facts, and a fourth that finds nothing new, because the ancestor rule is recursive: each round adds one generation.

## 18.5 Local search

**Definition 18.12 (Local search, 2-opt move, WalkSAT).**

*Local search* starts from a solution and repeatedly replaces it by a better one among its neighbours, solutions that differ by a small change. A *2-opt move* on a tour removes two edges $ab$ and $ce$ and reconnects the tour with $ac$ and $be$, reversing the segment between. *WalkSAT* flips one variable of an unsatisfied clause chosen at random: with some probability a random one, otherwise the one whose flip falsifies the fewest satisfied clauses.

```python
def two_opt(points, tour):
    """Reverse a segment whenever that shortens the tour, until no reversal does."""
    tour, improved = list(tour), True
    while improved:
        improved = False
        for i in range(1, len(tour) - 1):
            for j in range(i + 1, len(tour)):
                a, b = points[tour[i - 1]], points[tour[i]]
                c, e = points[tour[j]], points[tour[(j + 1) % len(tour)]]
                if dist(a, c) + dist(b, e) < dist(a, b) + dist(c, e) - 1e-9:
                    tour[i:j + 1] = reversed(tour[i:j + 1])
                    improved = True
    return tour
```

***Listing 18.12.** 2-opt: reverse a segment while that shortens the tour. code/bachelor-3/18-hard-problems/listings/tsp.py*

A tour no [2-opt move](#def-b3-hard-problems-local-search) improves crosses itself nowhere, since uncrossing two crossing edges shortens a Euclidean tour. On the 200 sets of 12 places ([Output 18.3](#out-b3-hard-problems-tsp)), 2-opt after [tree doubling](#def-b3-hard-problems-tsp) finds the optimum 103 times and stays within 16% of it. There is no guarantee: the 2-opt optimum can be a local optimum far from the best. S. Lin and B. W. Kernighan’s heuristic of 1973 searches tours that differ from the current one in more than two edges; simulated annealing accepts some worsening moves, with a probability that decreases over time, to escape local optima. Both are told here.

```python
def walksat(clauses, n, rng, noise=0.5, max_flips=20_000):
    value = {v: rng.random() < 0.5 for v in range(1, n + 1)}

    def sat(c):
        return any(value[abs(x)] == (x > 0) for x in c)

    def breaks(v):  # clauses satisfied now that flipping v would falsify
        value[v] = not value[v]
        count = sum(1 for c in clauses if v in map(abs, c) and not sat(c))
        value[v] = not value[v]
        return count
    for flips in range(max_flips):
        unsat = [c for c in clauses if not sat(c)]
        if not unsat:
            return value, flips
        c = rng.choice(unsat)
        if rng.random() < noise:
            v = abs(rng.choice(c))  # a random walk step
        else:
            v = min((abs(x) for x in c), key=breaks)  # the greedy step
        value[v] = not value[v]
    return None, max_flips
```

***Listing 18.13.** [WalkSAT](#def-b3-hard-problems-local-search), with half its steps random. code/bachelor-3/18-hard-problems/listings/walksat.py*

```
$ python walksat.py
  n   clauses   CDCL says   WalkSAT flips (5 seeded runs)
 20        80       UNSAT   20,000 20,000 20,000 20,000 20,000
 40       160         SAT      275  2,918    152    568    896
 60       240         SAT      202    342    269    278  1,290
 80       320         SAT    3,704  3,784  9,751    592    385
```

***Output 18.7.** [WalkSAT](#def-b3-hard-problems-local-search) on random 3-SAT at 4 clauses per variable, five seeds each. The first formula is unsatisfiable, and [WalkSAT](#def-b3-hard-problems-local-search) spends its whole budget without being able to say so.*

[WalkSAT](#def-b3-hard-problems-local-search) is described in Bart Selman, Henry Kautz and Bram Cohen’s paper on [local search](#def-b3-hard-problems-local-search) strategies for satisfiability of 1993.

It finds an assignment of a satisfiable formula often in a few hundred flips, but the counts vary by a factor of 25 from one seed to the next, and on an unsatisfiable formula it can only give up. [Local search](#def-b3-hard-problems-local-search) answers yes; only a complete solver, such as CDCL, answers no.

## 18.6 Exercises

**Exercise 18.1 ★.**

A path of 7 vertices $1 - 2 - \cdots - 7$. `matching_cover` reads the edges in order. Which cover does it return, what is the smallest cover, and what is the ratio?

**Solution of Exercise 18.1.**

Edge $12$ joins the matching, $23$ is covered, $34$ joins, $45$ is covered, $56$ joins, $67$ is covered: the cover is $\{1, \ldots, 6\}$, six vertices. The smallest cover is $\{2, 4, 6\}$: three vertices, since the three disjoint edges $12$, $34$, $56$ need one each. Ratio $6/3 = 2$.

**Exercise 18.2 ★.**

Run greedy set cover by hand on $U = \{1, \ldots, 6\}$ with $S_1 = \{1, 2, 3, 4\}$, $S_2 = \{1, 2, 5\}$, $S_3 = \{3, 4, 6\}$, $S_4 = \{5, 6\}$. Is the result optimal?

**Solution of Exercise 18.2.**

$S_1$ covers 4 new elements; then $S_4$ covers 5 and 6 (2 new, against 1 for $S_2$ and 1 for $S_3$). Two sets, $\{S_1, S_4\}$, and no single set covers $U$: optimal.

**Exercise 18.3 ★.**

Unit-propagate $x_1 \wedge (\neg x_1 \vee x_2) \wedge (\neg x_2 \vee \neg x_3) \wedge (x_3 \vee x_4 \vee \neg x_1) \wedge (\neg x_4 \vee x_5)$. Which variables are set, and in which order?

**Solution of Exercise 18.3.**

$x_1$ is a unit: true. Then $\neg x_1 \vee x_2$ is unit: $x_2$ true. Then $\neg x_2 \vee \neg x_3$: $x_3$ false. Then $x_3 \vee x_4 \vee \neg x_1$: $x_4$ true. Then $\neg x_4 \vee x_5$: $x_5$ true. Every variable is set, in the order $x_1, x_2, x_3, x_4, x_5$, and every clause holds.

**Exercise 18.4 ★.**

From [Output 18.4](#out-b3-hard-problems-knapsack), predict the number of nodes without the bound for 26 items. Why can the count with the bound go down from 14 to 18 items?

**Solution of Exercise 18.4.**

Without the bound the count grows by about 15.5 for every four items, close to $2^4 = 16$: about 80 million nodes for 26 items. With the bound, the count depends on how close the fractional bound is to the true optimum on the instance, not only on its size; on the instance of 18 items it prunes more of the tree than on that of 14.

**Exercise 18.5 ★★.**

`exercises/ex5_learning.py` learns only the negation of the [unique implication point](#def-b3-hard-problems-cdcl) and jumps back to level 0. Find a satisfiable formula it declares unsatisfiable, explain why the clause it learns is not implied by the formula, and fix it.

**Solution of Exercise 18.5.**

On the nine clauses of `test_exercise_5_buggy_is_unsound_and_fixed_is_right`, satisfiable, the buggy solver answers unsatisfiable. The first-UIP clause is $\neg u \vee \ell_1 \vee \cdots \vee \ell_k$, where the $\ell_i$ are literals of earlier levels; resolution derives it from the formula, so it is implied. Dropping the $\ell_i$ leaves the unit $\neg u$, which says $u$ is false whatever the earlier decisions; that is implied only if the conflict follows from $u$ alone, which is not the case when the earlier literals took part. The solver then asserts a consequence of its own decisions as a fact, and later refutes a satisfiable formula. The fix keeps the earlier literals and backjumps to the highest of their levels: `Fixed` uses the analysis of [Listing 18.7](#lst-b3-hard-problems-analyse) unchanged.

**Exercise 18.6 ★★.**

Write `one_tree_bound(points)`: a minimum spanning tree of all the points but the first, plus the two shortest edges from the first. Prove it never exceeds the shortest tour. It is tested against brute force.

**Solution of Exercise 18.6.**

`exercises/ex6_one_tree.py` uses `minimum_spanning_tree` on the points but the first and adds the two shortest distances from the first. Any tour consists of the two tour edges at the first point, plus a path through all the others, which is a spanning tree of them: so the tour weighs at least the minimum spanning tree plus the two shortest edges at the first point (`test_tours`). For the van it gives 13,594 m.

**Exercise 18.7 ★★.**

Prove [Theorem 18.2](#thm-b3-hard-problems-vertex-cover) in full: the result is a cover, it is at most twice the smallest, and the factor 2 is reached for every even number of vertices.

**Solution of Exercise 18.7.**

Facts used: a matching’s edges share no vertex; every cover contains an end of every edge.

Let $M$ be the matching built. An edge $uv$ not covered would have neither end in a matched edge, and the loop would have added it to $M$: so the result is a cover, of size $2|M|$. Any cover $C$ contains an end of each edge of $M$, and these ends are distinct, so $|C| \ge |M|$, and $2|M| \le 2|C|$. Tightness: on $k$ disjoint edges ($2k$ vertices) the algorithm takes all $2k$ vertices and $k$ suffice; on the complete bipartite graph of the chapter’s figure, the same.

**Exercise 18.8 ★★.**

Prove that `horn_sat` ([Listing 18.10](#lst-b3-hard-problems-horn)) runs in time linear in the total number of literals.

**Solution of Exercise 18.8.**

Facts used: a clause enters the queue only when its counter reaches 0, which happens once.

Building `waiting` and `uses` reads every literal once. Each clause is popped from the queue at most once, and its head is found by reading its literals: total, the size of the formula. A variable is made true at most once, and then each clause in which it occurs negatively has its counter decremented once: over all variables, at most the number of negative literals. Every step is constant time, so the whole is linear in the number of literals.

**Exercise 18.9 ★★.**

How many entries does the Held–Karp table hold for $n$ places, and how many steps does filling it take? Give the numbers for the van’s 12 places, and compare with the number of tours.

**Solution of Exercise 18.9.**

One entry per pair $(S, j)$ with $S \subseteq \{1, \ldots, n - 1\}$ and $j \in S$: $(n - 1)2^{n - 2}$ entries, each a minimum over at most $n - 2$ predecessors, so $O(n^2 2^n)$ steps. For $n = 12$: $11 \times 2^{10} = 11{,}264$ entries and at most about $11{,}264 \times 10 \approx 113{,}000$ steps (`test_van_bounds_and_table_size`), against $11!/2 = 19{,}958{,}400$ tours.

**Exercise 18.10 ★★★.**

Prove [Theorem 18.4](#thm-b3-hard-problems-set-cover). (When greedy takes a set covering $k$ new elements, charge each of them $1/k$. Show that the elements of any set $S$ of an optimal cover are charged at most $H(|S|)$ in all.)

**Solution of Exercise 18.10.**

Facts used: $\sum_{j \le m} 1/j = H(m)$; greedy picks a set covering the most uncovered elements.

When greedy picks a set that covers $k$ new elements, charge each of them $1/k$; the total charge is the number of sets greedy takes. Let $S$ be a set of an optimal cover, and list its elements in the order greedy covers them, $e_1, \ldots, e_m$. When $e_i$ is covered, at least $m - i + 1$ elements of $S$ are still uncovered, so $S$ itself would cover that many; greedy’s choice covers at least as many, and $e_i$ is charged at most $1/(m - i + 1)$. The elements of $S$ are charged at most $1/m + \cdots + 1/1 = H(m) \le H(n)$. Every element lies in some set of the optimal cover, so the total charge is at most $H(n)$ times the number of its sets. Finally $H(n) \le 1 + \int_1^n dx/x = 1 + \ln n$.

**Exercise 18.11 ★★★.**

Prove that, for every constant $\rho \ge 1$, no polynomial-time algorithm approximates the general travelling salesman problem within $\rho$ unless $\mathrm{P} = \mathrm{NP}$.

**Solution of Exercise 18.11.**

Facts used: [Hamiltonian cycle](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-problems) is [NP-complete](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-reduction) ([Chapter 17](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#ch-b3-np-completeness)).

Suppose an algorithm $A$ returns a tour within $\rho$ of the optimum in polynomial time. Given a graph $G$ on $n$ vertices, give each edge of $G$ length 1 and each other pair length $\rho n + 1$; this takes polynomial time. If $G$ has a [Hamiltonian cycle](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-problems), the optimum is $n$ and $A$ returns a tour of length at most $\rho n$. If not, every tour uses a pair that is not an edge and has length at least $\rho n + 1 + (n - 1) > \rho n$. So comparing $A$’s tour with $\rho n$ decides [Hamiltonian cycle](https://one-course.com/books/computer-science/5/en/chapter/17-np-completeness#def-b3-np-completeness-problems), and $\mathrm{P} = \mathrm{NP}$. The lengths break the triangle inequality, which is why the metric case escapes.

**Exercise 18.12 ★★★.**

Add restarts to `cdcl.py` by overriding `restart_now`: restart after $16 \cdot r_i$ conflicts in the $i$-th run, where $r_i$ follows the sequence $1, 1, 2, 1, 1, 2, 4, 1, 1, 2, \ldots$ Explain why the solver stays complete, and measure the conflicts on the random formulas of 60, 80 and 100 variables of seed 18.

**Solution of Exercise 18.12.**

`exercises/ex12_restarts.py`: `Restarting` counts conflicts and, after $16 \cdot r_i$ of them, returns true from `restart_now`, so the main loop backjumps to level 0. The solver stays complete: the learned clauses are kept, each is implied by the formula so no solution is lost, and the run lengths grow without bound, so eventually a run is long enough to finish. Measured (`test_exercise_12_counts`): 119 conflicts without restarts against 90 with 4 restarts for 60 variables; 289 against 212 with 8 for 80; but 101 against 169 with 6 for 100. Restarts help on some formulas and hurt on others; solvers keep them because they cut the very long runs that an unlucky early decision causes.

## 18.7 Weekend problem

**Problem 18.1.**

Weekend problem — The delivery van of Brenmoor

A van leaves the Town Square, serves 11 other places and returns. Distances are straight lines between the coordinates of the town’s places, in metres. This problem compares the exact tour, the tour [tree doubling](#def-b3-hard-problems-tsp) guarantees and the tour 2-opt finds, with the counts of [Output 18.3](#out-b3-hard-problems-tsp).

**Part I — The exact tour.**

1. How many different tours visit the 12 places, counting a tour and its reverse once?
2. Why can Held–Karp fix the Town Square as the start without losing any tour?
3. State the recurrence for the shortest path from place 0 through a set $S$ ending at $j$ .
4. How many table entries does the program compute for 12 places? ( [Exercise 18.9](#exo-b3-hard-problems-9) .)
5. Why does the program take a fraction of a second on 12 places, and about how much longer would 24 take?
6. The optimum is 16,635 m. Is a tour of 16,600 m possible?

**Part II — Tree doubling.**

7. Why are straight-line distances a metric?
8. The minimum spanning tree weighs 11,367 m. Why is that a lower bound on every tour?
9. What bound on the tree-doubling tour follows from the proof of [Theorem 18.6](#thm-b3-hard-problems-tree-doubling) ? Is it met?
10. Where in the proof is the triangle inequality used?
11. The tree-doubling tour is 18,427 m. What ratio does the van see, and what ratio does the theorem promise?
12. The 1-tree bound is 13,594 m. Which lower bound is better, and how much better?
13. With both lower bounds alone, without Held–Karp, what can be said about how close [tree doubling](#def-b3-hard-problems-tsp) is to optimal?

**Part III — 2-opt.**

14. Describe one [2-opt move](#def-b3-hard-problems-local-search) as a change to the list of places.
15. Why does `two_opt` stop?
16. After 2-opt the van’s tour is 17,617 m. Is it a local optimum, and is it the optimum?
17. Why can a tour with two crossing edges not be 2-optimal?
18. How many [2-opt moves](#def-b3-hard-problems-local-search) does one pass over a tour of $n$ places examine?
19. Why is 2-opt started from the tree-doubling tour rather than from a random one?

**Part IV — Measured over many instances.**

20. Over 200 seeded choices of 12 places out of 30, what are the worst and mean ratios of [tree doubling](#def-b3-hard-problems-tsp) ?
21. Is the worst ratio, 1.456, consistent with the theorem? What would contradict it?
22. What do 2-opt’s mean ratio of 1.022 and worst of 1.156 add?
23. In how many instances does 2-opt reach the optimum, and what does that say about local optima?
24. Why can such measurements never replace the proof of the factor 2?
25. The van’s company grows to 60 places. Which of the three methods still runs, and which guarantee remains?

**Solution of Problem 18.1.**

**1.** $11!/2 = 19{,}958{,}400$.

**2.** Every tour passes through the Town Square; rotating it to start there gives the same cycle.

**3.** With $D(\{j\}, j) = d(0, j)$,

$$
D(S, j) = \min_{k \in S \setminus \{j\}} \bigl( D(S \setminus \{j\}, k) + d(k, j) \bigr),
$$

and the tour is $\min_j D(\{1, \ldots, 11\}, j) + d(j, 0)$.

**4.** $11 \times 2^{10} = 11{,}264$.

**5.** About $10^5$ steps for 12 places ([Exercise 18.9](#exo-b3-hard-problems-9)); for 24, $23 \times 2^{22} \approx 10^8$ entries of about 22 steps each, some 20,000 times more, minutes in Python, with a table too large for this program’s dictionary.

**6.** No: Held–Karp is exact, so no tour is shorter than 16,635 m.

**7.** The straight line is the shortest path between two points, so going through a third point is never shorter.

**8.** Removing an edge from any tour leaves a spanning tree, which weighs at least the minimum one.

**9.** At most $2 \times 11{,}367 = 22{,}734$ m. Not met: 18,427 m, since the shortcuts save a great deal.

**10.** In replacing each skip of visited points by a straight segment.

**11.** $18{,}427 / 16{,}635 = 1.108$; the theorem promises at most 2.

**12.** The 1-tree, by $13{,}594 - 11{,}367 = 2{,}227$ m.

**13.** The optimum lies between 13,594 and 18,427 m, so [tree doubling](#def-b3-hard-problems-tsp) is within $18{,}427 / 13{,}594 = 1.36$ of it, a better guarantee for this instance than the factor 2.

**14.** Choose positions $i < j$ and reverse the places from $i$ to $j$; the edges into and out of the segment change.

**15.** Each move shortens the tour strictly, and there are finitely many tours.

**16.** It is a local optimum, since `two_opt` stops only when no move improves; it is not the optimum, 6% longer.

**17.** Uncrossing two crossing edges by a [2-opt move](#def-b3-hard-problems-local-search) shortens the tour, as the two diagonals of a convex quadrilateral add up to more than either pair of opposite sides.

**18.** The pairs $i < j$: about $n^2/2$.

**19.** It starts within a factor 2, so fewer moves are needed, and the local optimum reached tends to be good; from a random tour 2-opt also works, but takes more moves.

**20.** Worst 1.456, mean 1.216.

**21.** Yes, $1.456 \le 2$. A ratio above 2 on a metric instance would contradict it, and so would show a bug.

**22.** After 2-opt the tours are on average 2.2% above the optimum and at worst 15.6%.

**23.** In 103 of 200: the other 97 stop at a local optimum that is not the best.

**24.** They cover 200 instances of one kind; the proof covers every metric instance, including those no sample finds.

**25.** Held–Karp would need about $60^2 \times 2^{60}$ steps: not feasible. [Tree doubling](#def-b3-hard-problems-tsp) and 2-opt run in a fraction of a second; the factor 2 remains, and the 1-tree bound says how close the tour is on that instance.
