هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.
University Computer Science — Year 3 · السنة الجامعية 3
18Approximation and Exact Methods for Hard Problems
Chapter 17 showed that vertex cover, the travelling salesman problem and satisfiability are NP-complete: 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 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, 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 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 runs in polynomial time and returns, on every instance, a solution of cost at most 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 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 completes the proof; the figure after the output shows a tight case.
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
$ 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
18.1.1 Set cover
Definition 18.3 (Set cover problem)
The set cover problem: given a universe of elements and sets whose union is , choose as few sets as possible whose union is .
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.
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
Theorem 18.4 (Greedy set cover)
The greedy algorithm returns a cover at most times the smallest, and .
The bound is due to David Johnson in 1974 and László Lovász in 1975; Exercise 18.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
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 points whose distances satisfy the triangle inequality . 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 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 . The walk round the tree crosses every edge twice, a closed walk of length through every point. Skipping a visited point replaces two steps by , which is no longer by the triangle inequality. So the tour is at most . ∎
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 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 of places and each , the shortest path from place 0 through all of ending at .
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]
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
The delivery van of Brenmoor serves 12 of the town’s places, with straight-line distances between them.
$ 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
18.1.3 Problems with no good ratio
Definition 18.7 (Inapproximability)
A problem shows inapproximability at ratio when no polynomial-time algorithm achieves ratio unless .
Without the triangle inequality the travelling salesman has no constant ratio at all: an algorithm with ratio would decide whether a graph has a Hamiltonian cycle. Give the graph’s edges length 1 and every other pair length . A Hamiltonian cycle is a tour of length ; any other tour uses a non-edge and costs more than ; so the algorithm’s tour has length at most exactly when the graph has a Hamiltonian cycle (Exercise 18.11). Stronger results of this kind, showing that a constant ratio below some threshold is NP-hard 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. 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.
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
$ 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
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).
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 , , , , and decide at level 1, then at level 2. Propagation sets , then and , and is falsified. Resolving with the reason of gives ; with the reason of , . One literal of level 2 is left, : the first unique implication point. The learned clause says that and cannot both hold; the solver jumps back to level 1, where the clause is unit and sets false, without ever trying again.
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.
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
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
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
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 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).
The two solvers are compared below in decisions and conflicts, which do not depend on the machine. The pigeonhole formulas put pigeons in 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).
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
$ 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
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: is the rule “if then ”; 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. ∎
William Dowling and Jean Gallier published linear-time algorithms for Horn formulas in 1984. Forward chaining 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 run this way, or backwards from a goal; they are told here, not built.
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)}
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")),
]
$ 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
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 and and reconnects the tour with and , 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.
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
A tour no 2-opt move improves crosses itself nowhere, since uncrossing two crossing edges shortens a Euclidean tour. On the 200 sets of 12 places (Output 18.3), 2-opt after tree doubling 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.
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
$ 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
WalkSAT is described in Bart Selman, Henry Kautz and Bram Cohen’s paper on 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 answers yes; only a complete solver, such as CDCL, answers no.
18.6 Exercises
Exercise 18.1 ★
A path of 7 vertices . matching_cover reads the edges in order. Which cover does it return, what is the smallest cover, and what is the ratio?
Solution
Solution of Exercise 18.1.
Edge joins the matching, is covered, joins, is covered, joins, is covered: the cover is , six vertices. The smallest cover is : three vertices, since the three disjoint edges , , need one each. Ratio .
Exercise 18.2 ★
Run greedy set cover by hand on with , , , . Is the result optimal?
Solution
Solution of Exercise 18.2.
covers 4 new elements; then covers 5 and 6 (2 new, against 1 for and 1 for ). Two sets, , and no single set covers : optimal.
Exercise 18.3 ★
Unit-propagate . Which variables are set, and in which order?
Solution
Solution of Exercise 18.3.
is a unit: true. Then is unit: true. Then : false. Then : true. Then : true. Every variable is set, in the order , and every clause holds.
Exercise 18.4 ★
From Output 18.4, 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
Solution of Exercise 18.4.
Without the bound the count grows by about 15.5 for every four items, close to : 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 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
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 , where the are literals of earlier levels; resolution derives it from the formula, so it is implied. Dropping the leaves the unit , which says is false whatever the earlier decisions; that is implied only if the conflict follows from 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 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
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 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
Solution of Exercise 18.7.
Facts used: a matching’s edges share no vertex; every cover contains an end of every edge.
Let be the matching built. An edge not covered would have neither end in a matched edge, and the loop would have added it to : so the result is a cover, of size . Any cover contains an end of each edge of , and these ends are distinct, so , and . Tightness: on disjoint edges ( vertices) the algorithm takes all vertices and suffice; on the complete bipartite graph of the chapter’s figure, the same.
Exercise 18.8 ★★
Prove that horn_sat (Listing 18.10) runs in time linear in the total number of literals.
Solution
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 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
Solution of Exercise 18.9.
One entry per pair with and : entries, each a minimum over at most predecessors, so steps. For : entries and at most about steps (test_van_bounds_and_table_size), against tours.
Exercise 18.10 ★★★
Prove Theorem 18.4. (When greedy takes a set covering new elements, charge each of them . Show that the elements of any set of an optimal cover are charged at most in all.)
Solution
Solution of Exercise 18.10.
Facts used: ; greedy picks a set covering the most uncovered elements.
When greedy picks a set that covers new elements, charge each of them ; the total charge is the number of sets greedy takes. Let be a set of an optimal cover, and list its elements in the order greedy covers them, . When is covered, at least elements of are still uncovered, so itself would cover that many; greedy’s choice covers at least as many, and is charged at most . The elements of are charged at most . Every element lies in some set of the optimal cover, so the total charge is at most times the number of its sets. Finally .
Exercise 18.11 ★★★
Prove that, for every constant , no polynomial-time algorithm approximates the general travelling salesman problem within unless .
Solution
Solution of Exercise 18.11.
Facts used: Hamiltonian cycle is NP-complete (Chapter 17).
Suppose an algorithm returns a tour within of the optimum in polynomial time. Given a graph on vertices, give each edge of length 1 and each other pair length ; this takes polynomial time. If has a Hamiltonian cycle, the optimum is and returns a tour of length at most . If not, every tour uses a pair that is not an edge and has length at least . So comparing ’s tour with decides Hamiltonian cycle, and . 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 conflicts in the -th run, where follows the sequence Explain why the solver stays complete, and measure the conflicts on the random formulas of 60, 80 and 100 variables of seed 18.
Solution
Solution of Exercise 18.12.
exercises/ex12_restarts.py: Restarting counts conflicts and, after 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 guarantees and the tour 2-opt finds, with the counts of Output 18.3.
Part I — The exact tour.
- How many different tours visit the 12 places, counting a tour and its reverse once?
- Why can Held–Karp fix the Town Square as the start without losing any tour?
- State the recurrence for the shortest path from place 0 through a set ending at .
- How many table entries does the program compute for 12 places? (Exercise 18.9.)
- Why does the program take a fraction of a second on 12 places, and about how much longer would 24 take?
- The optimum is 16,635 m. Is a tour of 16,600 m possible?
Part II — Tree doubling.
- Why are straight-line distances a metric?
- The minimum spanning tree weighs 11,367 m. Why is that a lower bound on every tour?
- What bound on the tree-doubling tour follows from the proof of Theorem 18.6? Is it met?
- Where in the proof is the triangle inequality used?
- The tree-doubling tour is 18,427 m. What ratio does the van see, and what ratio does the theorem promise?
- The 1-tree bound is 13,594 m. Which lower bound is better, and how much better?
- With both lower bounds alone, without Held–Karp, what can be said about how close tree doubling is to optimal?
Part III — 2-opt.
- Describe one 2-opt move as a change to the list of places.
- Why does
two_optstop? - After 2-opt the van’s tour is 17,617 m. Is it a local optimum, and is it the optimum?
- Why can a tour with two crossing edges not be 2-optimal?
- How many 2-opt moves does one pass over a tour of places examine?
- Why is 2-opt started from the tree-doubling tour rather than from a random one?
Part IV — Measured over many instances.
- Over 200 seeded choices of 12 places out of 30, what are the worst and mean ratios of tree doubling?
- Is the worst ratio, 1.456, consistent with the theorem? What would contradict it?
- What do 2-opt’s mean ratio of 1.022 and worst of 1.156 add?
- In how many instances does 2-opt reach the optimum, and what does that say about local optima?
- Why can such measurements never replace the proof of the factor 2?
- The van’s company grows to 60 places. Which of the three methods still runs, and which guarantee remains?
Solution
Solution of Problem 18.1.
1. .
2. Every tour passes through the Town Square; rotating it to start there gives the same cycle.
3. With ,
and the tour is .
4. .
5. About steps for 12 places (Exercise 18.9); for 24, 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 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. ; the theorem promises at most 2.
12. The 1-tree, by m.
13. The optimum lies between 13,594 and 18,427 m, so tree doubling is within of it, a better guarantee for this instance than the factor 2.
14. Choose positions and reverse the places from to ; 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 shortens the tour, as the two diagonals of a convex quadrilateral add up to more than either pair of opposite sides.
18. The pairs : about .
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, . 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 steps: not feasible. Tree doubling 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.
المصطلحات المعرَّفة في هذا الفصل
- Approximation algorithm, approximation ratio, maximal matching
- Horn clause, Horn-SAT, forward chaining
- Inapproximability
- Local search, 2-opt move, WalkSAT
- Metric travelling salesman problem, tree doubling
- Relaxed problem, relaxation bound
- Set cover problem
- Watched literals, solver implication graph, conflict clause, clause learning, unique implication point, backjumping, CDCL solver