计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 3 · 本科三年级

17NP-Completeness

Chapter 16 defined NP, the problems whose yes-answers have certificates that are quick to check, and left open whether they can all be solved quickly. Nobody knows. What is known is that thousands of problems from scheduling, routing, packing and logic are equally hard: a fast algorithm for any one of them would give fast algorithms for all of NP. This chapter proves the first such result, the Cook–Levin theorem, by turning the run of any nondeterministic machine into a Boolean formula, and then spreads it by reductions, each one a program tested against brute force: satisfiability to 3-SAT, to independent set, clique and vertex cover, to 3-colouring, to subset sum. It ends with what such a proof tells an engineer: which special cases are easy, and why a “polynomial” dynamic program can still be exponential.

You already know

A formula in conjunctive normal form is a conjunction of clauses, each a disjunction of literals; SAT asks whether it has a satisfying assignment, and kk-SAT is SAT for clauses of at most kk literals (Year 1 volume). A strongly connected component of a directed graph is a maximal set of vertices that can all reach one another; the components can be found in linear time, and contracting them leaves a graph with no cycle (Year 1 volume). A vertex cover of a graph is a set of vertices touching every edge (Year 2 volume). Dynamic programming fills a table of answers to subproblems (Year 1 volume). P, NP and verifiers are those of Chapter 16.

17.1 Polynomial reductions

Definition 17.1 (Polynomial-time reduction, NP-hard, NP-complete)

A polynomial-time reduction from a problem AA to a problem BB is a many-one reduction ff computable in polynomial time: x∈Ax \in A if and only if f(x)∈Bf(x) \in B. We write A≤pBA \le_p B. A problem BB is NP-hard when A≤pBA \le_p B for every AA in NP, and NP-complete when, in addition, BB is in NP.

Reductions compose: if A≤pBA \le_p B and B≤pCB \le_p C, then A≤pCA \le_p C, since a polynomial of a polynomial is a polynomial (the output of the first reduction has polynomial size). And they carry speed one way: if A≤pBA \le_p B and B∈PB \in \mathrm{P}, then A∈PA \in \mathrm{P}. So one NP-complete problem in P would put all of NP in P; and to prove a new problem BB NP-complete it suffices to show B∈NPB \in \mathrm{NP} and A≤pBA \le_p B for one known NP-complete AA. The direction matters: the reduction goes from the known hard problem to the new one. Reducing the new problem to SAT shows only that it is no harder than SAT.

Richard Karp introduced completeness by polynomial-time many-one reductions in 1972 and used it to show 21 problems NP-complete.

Michael Garey and David Johnson’s book of 1979 lists over 300. All of them rest on a first one.

17.2 The Cook–Levin theorem

Theorem 17.2 (Cook–Levin theorem)

SAT is NP-complete.

Stephen Cook published it in 1971, with a different notion of reduction; Leonid Levin, working independently in the Soviet Union, published an equivalent result for search problems in 1973; the proof with polynomial-time reductions is Karp’s.

Proof. SAT is in NP: an assignment is a certificate, checked clause by clause. Let AA be in NP, decided by a nondeterministic machine NN in time ncn^c (Definition 16.3). For an input ww of length nn, let t=nct = n^c. A run of NN on ww is a tableau: t+1t + 1 rows, each a configuration written as # u q v #\#\,u\,q\,v\,\# with the state qq just left of the cell under the head, all padded to the same width W=O(t)W = O(t). Build the formula φw\varphi_w on the variables xi,j,sx_{i,j,s}, “cell jj of row ii holds symbol ss”, with four parts.

  • Cells: each cell holds exactly one symbol, a clause of all its symbols and a clause ¬xi,j,s∨¬xi,j,s′\neg x_{i,j,s} \vee \neg x_{i,j,s'} for each pair.
  • Start: row 0 is the start configuration on ww, one unit clause per cell.
  • Accept: some cell of some row holds the accepting state, one clause.
  • Windows: every 2×32 \times 3 window, three adjacent cells of a row and the three below, is legal, that is, occurs in some configuration and one of its successors.

Only one cell per row holds a state, and a step changes only the cells next to it; so if every window is legal, each row is a successor of the one above, and the tableau is an accepting run. Conversely an accepting run fills a tableau whose windows are all legal, once its last configuration is repeated down to the last row: an accepting configuration counts as its own successor, as it does in cook_levin.py. So φw\varphi_w is satisfiable if and only if NN accepts ww. The legal windows form a fixed finite set, depending on NN only. The formula has O(t2)O(t^2) variables and O(t2)O(t^2) clauses of constant size, and is written in polynomial time. ∎

The window condition says “one of the legal windows is here”, a disjunction of conjunctions. cook_levin.py writes it in conjunctive normal form with one new variable yy per window and position, a clause “some yy is true” and clauses y⇒y \Rightarrow each of its six cells. It builds the formula for a three-state machine that guesses where the pair 11 begins in its input, and dpll.py, a plain DPLL solver that Chapter 18 develops, finds the accepting run.

def formula(word, steps):
    width = max(len(word), steps + 1) + 3  # room for the input and for the head
    num = {}

    def x(i, j, s):  # variable "cell j of row i holds symbol s"
        return num.setdefault((i, j, s), len(num) + 1)
    clauses = []
    for i, j in itertools.product(range(steps + 1), range(width)):
        clauses.append([x(i, j, s) for s in SYMBOLS])  # at least one symbol
        clauses += [[-x(i, j, s), -x(i, j, t)]  # at most one
                    for s, t in itertools.combinations(SYMBOLS, 2)]
    start = ("#", "q0", *word, *"_" * (width - len(word) - 3), "#")
    clauses += [[x(0, j, s)] for j, s in enumerate(start)]
    clauses.append([x(i, j, "qa") for i in range(steps + 1) for j in range(width)])
    windows = legal_windows(width)
    for i, j in itertools.product(range(steps), range(width - 2)):
        choice = []
        for top, bottom in windows:  # y means "this legal window is here"
            y = num.setdefault(("w", i, j, top, bottom), len(num) + 1)
            choice.append(y)
            clauses += [[-y, x(i, j + d, top[d])] for d in range(3)]
            clauses += [[-y, x(i + 1, j + d, bottom[d])] for d in range(3)]
        clauses.append(choice)
    return clauses, num, width, len(windows)
Listing 17.1. The tableau formula: cells, start row, acceptance, windows. code/bachelor-3/17-np-completeness/listings/cook_levin.py
$ python cook_levin.py
input 011, 3 steps: tableau 4 x 7, 193 legal windows
3,091 variables (196 for cells), 18,009 clauses
#  q0 0  1  1  _  # 
#  0  q0 1  1  _  # 
#  0  1  q1 1  _  # 
#  0  1  1  qa _  # 
Output 17.1. The formula for three steps on 011, and the tableau read from its satisfying assignment: the machine guessed right at the first 1.
The tableau of , one configuration per row. The formula forces every 2 × 3 window to be one of the 193 legal ones.
The tableau of Output 17.1, one configuration per row. The formula forces every 2×32 \times 3 window to be one of the 193 legal ones.

17.3 A chain of reductions

Every reduction below is a function in a listing, run on one small formula, and tested on random small formulas by comparing brute force on both sides; the tests generate the formulas with the hypothesis library.

Definition 17.3 (Independent set, clique, Hamiltonian cycle, subset sum problem)

An independent set of a graph is a set of pairwise non-adjacent vertices; a clique is a set of pairwise adjacent ones. The decision problems ask whether one of size kk exists. A Hamiltonian cycle is a cycle through every vertex exactly once. The subset sum problem asks whether some of given positive integers add up to a target TT.

Definition 17.4 (Gadget)

A gadget is a small fixed piece of the instance a reduction builds, one per variable or per clause of the formula, whose possible solutions behave like the truth values or the satisfied clauses.

The reductions of the chapter. Each arrow A B is A _p B; the dashed one is told, not built.
The reductions of the chapter. Each arrow A→BA \to B is A≤pBA \le_p B; the dashed one is told, not built.

17.3.1 From SAT to 3-SAT

A clause of one or two literals is padded with new variables taken with both signs, so that the new clauses hold exactly when the old one does; a clause ℓ1∨⋯∨ℓk\ell_1 \vee \cdots \vee \ell_k with k>3k > 3 becomes a chain (ℓ1∨ℓ2∨y1)(¬y1∨ℓ3∨y2)⋯(¬yk−3∨ℓk−1∨ℓk)(\ell_1 \vee \ell_2 \vee y_1)(\neg y_1 \vee \ell_3 \vee y_2) \cdots (\neg y_{k-3} \vee \ell_{k-1} \vee \ell_k). If some ℓi\ell_i is true, set the yys before its clause to true and the others to false; if all ℓi\ell_i are false, the chain forces y1y_1, then y2y_2, …, and the last clause fails.

def to_3sat(clauses):
    fresh = max(variables(clauses), default=0)
    out = []
    for c in clauses:
        if len(c) == 1:  # (a): all four ways to fill two new variables
            y, z = fresh + 1, fresh + 2
            fresh += 2
            out += [[c[0], s * y, t * z] for s in (1, -1) for t in (1, -1)]
        elif len(c) == 2:  # (a or b): one new variable, both signs
            fresh += 1
            out += [[c[0], c[1], fresh], [c[0], c[1], -fresh]]
        elif len(c) == 3:
            out.append(list(c))
        else:  # a chain: (l1 or l2 or y1)(not y1 or l3 or y2)...(not y or l_k-1 or l_k)
            fresh += 1
            out.append([c[0], c[1], fresh])
            for lit in c[2:-2]:
                out.append([-fresh, lit, fresh + 1])
                fresh += 1
            out.append([-fresh, c[-2], c[-1]])
    return out
Listing 17.2. SAT to 3-SAT: every clause becomes clauses of exactly three literals. code/bachelor-3/17-np-completeness/listings/reduce_3sat.py
$ python reduce_3sat.py
SAT:   [[1], [-1, 2], [1, -2, 3, -4, 5], [-3, -5]]
3-SAT: [[1, 6, 7], [1, 6, -7], [1, -6, 7], [1, -6, -7], [-1, 2, 8], [-1, 2, -8], [1, -2, 9], [-9, 3, 10], [-10, -4, 5], [-3, -5, 11], [-3, -5, -11]]
4 clauses on 5 variables -> 11 clauses on 11 variables
satisfiable: True True
Output 17.2. A formula with clauses of one, two, five and two literals, and its 3-SAT version: 11 clauses, 6 new variables.

So 3-SAT, with clauses of exactly three literals, is NP-complete.

17.3.2 Independent set, clique, vertex cover

For a 3-CNF formula with mm clauses, build one vertex per literal occurrence, join the three vertices of each clause into a triangle, and join every pair of complementary literals xx and ¬x\neg x. Ask for an independent set of size k=mk = m. It can take at most one vertex per triangle, so it takes exactly one literal per clause, and never two complementary ones: making them true satisfies the formula. Conversely, a satisfying assignment makes one literal per clause true, and those mm vertices are independent.

def to_independent_set(clauses):
    vertices = [(j, lit) for j, c in enumerate(clauses) for lit in c]
    edges = []
    for a, b in itertools.combinations(range(len(vertices)), 2):
        (ja, la), (jb, lb) = vertices[a], vertices[b]
        if ja == jb or la == -lb:  # same clause, or contradictory literals
            edges.append((a, b))
    return vertices, edges, len(clauses)


def to_clique(n, edges, k):
    """An independent set of G is a clique of the complement of G."""
    present = set(edges)
    return n, [e for e in itertools.combinations(range(n), 2) if e not in present], k


def to_vertex_cover(n, edges, k):
    """S is independent if and only if the other n - |S| vertices cover every edge."""
    return n, edges, n - k
Listing 17.3. 3-SAT to independent set, then to clique and to vertex cover. code/bachelor-3/17-np-completeness/listings/reduce_is.py
$ python reduce_is.py
9 vertices, 15 edges, k = 3
vertices: [(0, 1), (0, -2), (0, 3), (1, -1), (1, 2), (1, 3), (2, -1), (2, -2), (2, -3)]
clique instance: k = 3 edges 21 ; vertex cover instance: k = 6
satisfiable = has an independent set of size k: 200 of 200 random formulas
Output 17.3. Nine vertices for three clauses; the brute-force check agrees on 200 random formulas.

The other two follow at once. A set is independent in a graph if and only if it is a clique in the complement graph. And SS is independent if and only if the other vertices cover every edge, so GG has an independent set of size kk if and only if it has a vertex cover of size n−kn - k (Exercise 17.7). From vertex cover a longer chain of gadgets reaches Hamiltonian cycle: each edge becomes a gadget of twelve vertices that a tour crosses in one of three ways, according to which end of the edge is in the cover. It is told here, not built.

17.3.3 3-colouring

Three colours, three special vertices T, F and B in a triangle: in any colouring they take the three colours, and their names fix what the colours mean. For each variable, xx and ¬x\neg x are joined to each other and to B, so one is coloured T and the other F. For each clause a∨b∨ca \vee b \vee c, an OR gadget takes aa and bb and gives an output vertex that can be coloured T if and only if aa or bb is; a second gadget takes that output and cc; its output is joined to F and B, so it must be T.

The gadget of one clause a b c: two OR gadgets, six vertices and twelve edges. If a and b are both F, then u_1 and v_1 must be T and B, which leaves F for o_1.
The gadget of one clause a∨b∨ca \vee b \vee c: two OR gadgets, six vertices and twelve edges. If aa and bb are both F, then u1u_1 and v1v_1 must be T and B, which leaves F for o1o_1.
def to_colouring(clauses, n):
    edges = [(T, F), (F, B), (B, T)]
    def lit(x):  # the vertex of literal x: 3, 4 for x_1, not x_1; 5, 6 for x_2 ...
        return 3 + 2 * (abs(x) - 1) + (x < 0)
    for i in range(1, n + 1):
        edges += [(lit(i), lit(-i)), (lit(i), B), (lit(-i), B)]
    size = 3 + 2 * n

    def gadget(a, b):  # OR gadget: a triangle u, v, out with u - a and v - b
        nonlocal size
        u, v, out = size, size + 1, size + 2
        size += 3
        edges.extend([(u, a), (v, b), (u, v), (v, out), (out, u)])
        return out
    for a, b, c in clauses:
        out = gadget(gadget(lit(a), lit(b)), lit(c))
        edges.extend([(out, F), (out, B)])  # the clause's output must be T
    return size, edges
Listing 17.4. 3-SAT to 3-colouring: the palette, a pair per variable, two OR gadgets per clause. code/bachelor-3/17-np-completeness/listings/reduce_col.py
$ python reduce_col.py
n = 3 variables, m = 2 clauses: 21 vertices, 36 edges
  2n + 6m + 3 = 21, 3n + 12m + 3 = 36
satisfiable = 3-colourable: 30 of 30 random formulas (0 unsatisfiable)
all 8 clauses on x1, x2, x3: satisfiable False, 3-colourable False
Output 17.4. The sizes match 2n+6m+32n + 6m + 3 vertices and 3n+12m+33n + 12m + 3 edges, and the eight clauses that forbid every assignment give a graph with no 3-colouring.

Exercise 17.10 proves the reduction correct.

17.3.4 Subset sum

Numbers can simulate clauses too, if their digits never carry. For nn variables and mm clauses, write numbers of n+mn + m decimal digits. For each variable xix_i, two numbers yiy_i and ziz_i have a 1 in digit ii; yiy_i also has a 1 in the digit of each clause containing xix_i, and ziz_i in each clause containing ¬xi\neg x_i. Each clause also gets two slack numbers with a 1 in its digit. The target has a 1 in each variable digit and a 3 in each clause digit. A digit sums to at most 3+2=53 + 2 = 5, so nothing carries. Reaching a 1 in digit ii means choosing exactly one of yiy_i, ziz_i: an assignment. Reaching 3 in a clause digit needs at least one true literal, since the slacks give at most 2.

def to_subset_sum(clauses, n):
    m = len(clauses)

    def number(var_digit, clause_digits):  # digits: variables first, then clauses
        digits = [0] * (n + m)
        if var_digit is not None:
            digits[var_digit] = 1
        for j in clause_digits:
            digits[n + j] += 1
        return int("".join(map(str, digits)))
    numbers = []
    for i in range(1, n + 1):
        numbers.append(number(i - 1, [j for j, c in enumerate(clauses) if i in c]))
        numbers.append(number(i - 1, [j for j, c in enumerate(clauses) if -i in c]))
    for j in range(m):
        numbers += [number(None, [j]), number(None, [j])]  # slack: at most 2 more
    target = int("1" * n + "3" * m)
    return numbers, target
Listing 17.5. 3-SAT to subset sum, digit by digit. code/bachelor-3/17-np-completeness/listings/reduce_ss.py
$ python reduce_ss.py
numbers: [10010, 10001, 1001, 1010, 111, 100, 10, 10, 1, 1]
target:  11133
satisfiable = some subset reaches the target: 200 of 200 random formulas
Output 17.5. Ten numbers for three variables and two clauses (leading zeros are not shown), and the check on 200 random formulas.

17.4 co-NP

Definition 17.5 (co-NP)

co-NP is the class of problems whose complement is in NP: those whose no-instances have certificates checkable in polynomial time.

Is a formula a tautology, true under every assignment? A no-answer has a short certificate, a falsifying assignment; a yes-answer seems to need all 2n2^n assignments. Tautology is in co-NP, and it is co-NP-complete, since φ\varphi is a tautology exactly when ¬φ\neg \varphi is unsatisfiable. P is inside NP ∩\cap co-NP, because P is closed under complement. If some NP-complete problem were in co-NP, then NP would equal co-NP (Exercise 17.12). Factoring, as the decision problem “does NN have a factor below kk?”, is in NP ∩\cap co-NP, since the full factorisation, checked with a primality test, certifies both answers; it is not known to be in P, and if it were NP-complete, NP would equal co-NP.

17.5 What a proof of hardness tells an engineer

An NP-completeness proof says that no algorithm is known that is polynomial on every instance, and that finding one would settle P against NP. It does not say that the instances in front of you are hard. Three ways out are common: a special case that is easy, an algorithm polynomial in the numbers rather than their length, and the approximation and exact methods of Chapter 18.

Definition 17.6 (2-SAT, implication graph)

2-SAT is SAT for formulas whose clauses have at most two literals. The implication graph of such a formula has a vertex per literal and, for each clause a∨ba \vee b, the edges ¬a→b\neg a \to b and ¬b→a\neg b \to a.

Theorem 17.7 (2-SAT is in P)

A 2-CNF formula is unsatisfiable if and only if some variable xx and its negation ¬x\neg x lie in the same strongly connected component of the implication graph. This is decided, and a satisfying assignment found, in time linear in the size of the formula.

The edges are implications that every satisfying assignment respects, so a path from xx to ¬x\neg x and back makes both values impossible. The converse, and the assignment “xx is true when its component comes after that of ¬x\neg x in topological order”, are Exercise 17.9. Aspvall, Plass and Tarjan gave this linear-time algorithm in 1979.

def solve(clauses, n):
    comp = components(implication_graph(clauses, n))
    if any(comp[v] == comp[-v] for v in range(1, n + 1)):
        return None
    # x is true when its component comes later in topological order than not x's
    return {v: comp[v] > comp[-v] for v in range(1, n + 1)}
Listing 17.6. 2-SAT from the components, numbered in topological order by Kosaraju’s algorithm. code/bachelor-3/17-np-completeness/listings/two_sat.py
$ python two_sat.py
formula: [(1, 2), (-1, 3), (-2, -3), (2, 4), (-4, -1)]
components: {0: [1, -2, 3], 1: [-4], 2: [4], 3: [-1, 2, -3]}
assignment: {1: False, 2: True, 3: False, 4: True}
with (x1 or not x2) and (not x1 or not x2): None
Output 17.6. The components of a formula’s implication graph, the assignment they give, and an unsatisfiable extension.

So 2-SAT is linear while 3-SAT is NP-complete: the boundary between easy and hard can be one literal wide.

Definition 17.8 (Pseudo-polynomial algorithm, strongly NP-complete)

An algorithm is pseudo-polynomial when its running time is polynomial in the size of the input and in the magnitude of the numbers in it, rather than in their number of digits. A problem with numbers is strongly NP-complete when it remains NP-complete even with all its numbers bounded by a polynomial in the input size.

Subset sum has the dynamic program of the Year 1 volume: the set of sums reachable with the first ii numbers, for sums up to the target TT, filled in O(nT)O(nT) steps. That is polynomial in TT, but TT is written with about log⁡2T\log_2 T bits.

def dp_cells(numbers, target):
    """Decide subset sum; count the (number, sum) cells the table fills."""
    reachable, cells = [True] + [False] * target, 0
    for x in numbers:
        for s in range(target, x - 1, -1):  # downwards: each number used once
            cells += 1
            if reachable[s - x]:
                reachable[s] = True
    return reachable[target], cells
Listing 17.7. Subset sum by dynamic programming, counting the cells it fills. code/bachelor-3/17-np-completeness/listings/subset_dp.py
$ python subset_dp.py
n = 20 numbers of b bits; target = half their sum
 b   input bits   target T   table cells   found
 4           80         82         1,495   True
 8          160      1,408        25,363   True
12          240     20,675       372,170   True
16          320    375,952     6,767,155   True
Output 17.7. Four more bits per number multiply the table by about 16 while the input grows by 80 bits: exponential in the input size.

The reduction from 3-SAT builds targets with n+mn + m digits, so the dynamic program does not contradict NP-completeness. With numbers written in unary, or bounded by a polynomial, subset sum is in P; so, unless P = NP, it is not strongly NP-complete. 3-colouring has no numbers at all, and is NP-complete in the strong sense automatically.

17.6 Exercises

Exercise 17.1 ★

A student shows that a new scheduling problem SS is NP-complete by writing a polynomial-time reduction from SS to SAT. What has been proved, and what reduction is needed instead?

Solution

Solution of Exercise 17.1.

S≤pSATS \le_p \mathrm{SAT} proves that SS is in NP, no harder than SAT; nothing about its hardness. For NP-hardness the reduction must go the other way: from SAT, or another known NP-complete problem, to SS. With both, SS is NP-complete.

Exercise 17.2 ★

Apply the chain of Listing 17.2 to the clause x1∨¬x2∨x3∨x4∨¬x5x_1 \vee \neg x_2 \vee x_3 \vee x_4 \vee \neg x_5. Check by hand that the result is satisfied when x4x_4 is the only true literal of the clause (x1x_1 and x3x_3 false, x2x_2 and x5x_5 true), and say how the new variables are set.

Solution

Solution of Exercise 17.2.

(x1∨¬x2∨y1)(¬y1∨x3∨y2)(¬y2∨x4∨¬x5)(x_1 \vee \neg x_2 \vee y_1)(\neg y_1 \vee x_3 \vee y_2)(\neg y_2 \vee x_4 \vee \neg x_5). With x1x_1 and x3x_3 false and x2x_2 and x5x_5 true, x4x_4 is the only true literal: the first clause needs y1y_1 true, the second then needs y2y_2 true, and the third is satisfied by x4x_4 alone. The rule: the yys before the clause of the true literal are true, those after are false.

Exercise 17.3 ★

Draw the independent-set graph for (x1∨x2∨¬x3)∧(¬x1∨x3∨x2)(x_1 \vee x_2 \vee \neg x_3) \wedge (\neg x_1 \vee x_3 \vee x_2) and give an independent set of size 2 with the assignment it encodes.

Solution

Solution of Exercise 17.3.

Six vertices: a triangle x1,x2,¬x3x_1, x_2, \neg x_3 and a triangle ¬x1,x3,x2\neg x_1, x_3, x_2, plus the edges x1−¬x1x_1 - \neg x_1 and ¬x3−x3\neg x_3 - x_3. The two x2x_2 vertices are not joined, so {x2,x2′}\{x_2, x_2'\}, one per triangle, is independent of size 2: the assignment x2x_2 true, the others arbitrary. Another is {x1,x3}\{x_1, x_3\}: x1x_1 and x3x_3 true.

Exercise 17.4 ★

Predict the numbers and the target that to_subset_sum builds for the single clause x1∨¬x2∨x3x_1 \vee \neg x_2 \vee x_3, and give a subset reaching the target.

Solution

Solution of Exercise 17.4.

Digits x1x2x3∣c1x_1 x_2 x_3 \mid c_1: y1=1001y_1 = 1001, z1=1000z_1 = 1000, y2=100y_2 = 100, z2=101z_2 = 101, y3=11y_3 = 11, z3=10z_3 = 10, two slacks 11 and 11; target 11131113. For example y1+y2+y3+1=1001+100+11+1=1113y_1 + y_2 + y_3 + 1 = 1001 + 100 + 11 + 1 = 1113: all three variables true; the clause digit gets 1 from y1y_1, 1 from y3y_3 and 1 from a slack.

Exercise 17.5 ★★

exercises/ex5_clique.py has a reduction from 3-SAT to clique that joins every two literals that are not complementary. Find a formula on which it answers wrongly and fix it.

Solution

Solution of Exercise 17.5.

Joining literals of the same clause lets a clique take two literals from one clause and none from another. The eight clauses that forbid every assignment of x1,x2,x3x_1, x_2, x_3 form an unsatisfiable formula, yet the buggy graph has a clique of size 8: the literal x1x_1 occurs in four clauses and x2x_2 in four, and these eight occurrences are pairwise non-complementary, so all joined; a test checks it. The fix joins two occurrences only if they lie in different clauses and are not complementary; then a clique of size mm takes one literal per clause, consistently.

Exercise 17.6 ★★

Write colouring_to_sat(n, edges), a reduction from 3-colouring to SAT. It is tested against backtracking on random graphs.

Solution

Solution of Exercise 17.6.

exercises/ex6_col_to_sat.py: variables xv,cx_{v,c} for 3 colours; per vertex one clause xv,0∨xv,1∨xv,2x_{v,0} \vee x_{v,1} \vee x_{v,2} and three clauses ¬xv,a∨¬xv,b\neg x_{v,a} \vee \neg x_{v,b}; per edge uvuv and colour cc, ¬xu,c∨¬xv,c\neg x_{u,c} \vee \neg x_{v,c}. A colouring gives a satisfying assignment and back; 3n3n variables and 4n+3m4n + 3m clauses (test_exercise_6_colouring_to_sat).

Exercise 17.7 ★★

Prove that vertex cover is NP-complete, from independent set.

Solution

Solution of Exercise 17.7.

Vertex cover is in NP: the set is a certificate, checked edge by edge. Facts used: SS is independent if and only if V∖SV \setminus S covers every edge, since an edge with no end in V∖SV \setminus S has both ends in SS. Map (G,k)(G, k) to (G,n−k)(G, n - k): GG has an independent set of size kk if and only if it has a vertex cover of size n−kn - k. The map is computed in linear time, so independent set ≤p\le_p vertex cover, and vertex cover is NP-complete.

Exercise 17.8 ★★

Count the variables and clauses of the formula of Listing 17.1 for tt steps, width WW, 7 symbols and LL legal windows, and check the counts of Output 17.1.

Solution

Solution of Exercise 17.8.

Cell variables: 7(t+1)W7(t + 1)W. Window variables: one per legal window and per position, t(W−2)Lt(W - 2)L. Clauses: per cell, one “at least one” and (72)=21\binom{7}{2} = 21 “at most one”: 22(t+1)W22(t + 1)W; the start row, WW; acceptance, 1; per window position, 6L+16L + 1: t(W−2)(6L+1)t(W - 2)(6L + 1). For t=3t = 3, W=7W = 7, L=193L = 193: 196+15×193=3,091196 + 15 \times 193 = 3{,}091 variables and 616+7+1+15×1,159=18,009616 + 7 + 1 + 15 \times 1{,}159 = 18{,}009 clauses, as printed (test_cook_levin_counts_and_windows).

Exercise 17.9 ★★

Prove Theorem 17.7: if no xx shares a component with ¬x\neg x, the assignment of Listing 17.6 satisfies every clause. (Use the symmetry of the graph: a→ba \to b is an edge if and only if ¬b→¬a\neg b \to \neg a is.)

Solution

Solution of Exercise 17.9.

Facts used: the graph is symmetric, a→ba \to b being an edge if and only if ¬b→¬a\neg b \to \neg a is, so a path from aa to bb gives one from ¬b\neg b to ¬a\neg a, and the components come in mirror pairs; a satisfying assignment never has a true literal implying a false one along an edge.

If xx and ¬x\neg x share a component, x⇒¬xx \Rightarrow \neg x and ¬x⇒x\neg x \Rightarrow x along paths, so neither value is possible. Conversely, number the components in a topological order and make xx true when its component comes after that of ¬x\neg x. Suppose a clause a∨ba \vee b is false: aa and bb are false, so the component of ¬a\neg a comes after that of aa, and the same for bb. The edge ¬a→b\neg a \to b puts bb’s component at or after ¬a\neg a’s, and the edge ¬b→a\neg b \to a puts aa’s at or after ¬b\neg b’s. Then a≤¬a≤b≤¬b≤aa \le \neg a \le b \le \neg b \le a in the order, with aa strictly before ¬a\neg a: a contradiction. The algorithm finds the components and their order in linear time (test_two_sat).

Exercise 17.10 ★★★

Prove that the 3-colouring reduction is correct: the graph is 3-colourable if and only if the formula is satisfiable.

Solution

Solution of Exercise 17.10.

Facts used: in a 3-colouring the palette T, F, B takes three different colours, which we name by it; a literal vertex is adjacent to B, so it is T or F, and xx, ¬x\neg x differ.

The OR gadget on inputs aa, bb coloured T or F: if both are F, uu and vv avoid F, so they are T and B in some order, and the output, adjacent to both, is F. If aa is T, colour uu F, vv B (allowed, since bb is T or F) and the output T; if bb is T, symmetrically. So the output is F whenever both inputs are F, and it can be T when aa or bb is T. It is not always T or F: with aa T and bb F, the colouring uu F, vv T gives the output B. The first argument holds for any input that is F, literal or not.

If the graph is 3-colourable, read the assignment from the literal vertices. Each clause’s last output is adjacent to F and B, so it is T; then the first output and cc are not both F. If cc is not T it is F, being a literal, so the first output is not F, and then aa and bb are not both F: aa, bb or cc is T, and the clause is satisfied. Conversely, from a satisfying assignment colour the literals, then each gadget as above with output T whenever possible; the last output of each clause is T, compatible with its edges to F and B. Sizes are linear, so the reduction is polynomial.

Exercise 17.11 ★★★

Prove that subset sum is NP-complete, and explain why the dynamic program of Listing 17.7 does not show it is in P.

Solution

Solution of Exercise 17.11.

Subset sum is in NP: the subset is the certificate. The reduction of the chapter is correct. If the formula is satisfiable, take yiy_i or ziz_i as xix_i is true or false; each variable digit is 1, each clause digit has 1 to 3 from the literals, completed to 3 by slacks. If a subset reaches the target, no digit carries, since a digit’s total is at most 5; each variable digit is 1, so exactly one of yiy_i, ziz_i is chosen, an assignment; each clause digit is 3 with at most 2 from slacks, so some true literal is in the clause. The numbers have n+mn + m digits, written in polynomial time. The dynamic program takes O(nT)O(nT) steps, and here T≈10n+mT \approx 10^{n + m}: exponential in the input size, which is about (2n+2m)(n+m)(2n + 2m)(n + m) digits.

Exercise 17.12 ★★★

Prove that if some NP-complete problem is in co-NP, then NP=co-NP\mathrm{NP} = \mathrm{co\text{-}NP}.

Solution

Solution of Exercise 17.12.

Let CC be NP-complete and in co-NP. For AA in NP, A≤pCA \le_p C by a function ff; then A‾≤pC‾\overline{A} \le_p \overline{C} by the same ff, and C‾\overline{C} is in NP, so A‾\overline{A} is in NP: AA is in co-NP. So NP⊆co-NP\mathrm{NP} \subseteq \mathrm{co\text{-}NP}. For BB in co-NP, B‾\overline{B} is in NP, hence in co-NP, so BB is in NP: co-NP⊆NP\mathrm{co\text{-}NP} \subseteq \mathrm{NP}.

17.7 Weekend problem

Problem 17.1

Weekend problem — Timetabling the town’s exams

Brenmoor’s school sets its exams in a few time slots; two exams taken by a common student must not share a slot. Exams are vertices, clashes are edges, slots are colours. This problem shows that three slots make the problem NP-complete, with the gadgets of Listing 17.4, and that two slots do not.

Part I — The decision problem.

  1. State the timetabling problem with ss slots as a decision problem on graphs.
  2. Show it is in NP for every ss: what is the certificate, and how long does checking take?
  3. Six exams, A to F; clashes AB, BC, CA, CD, DE, EF, FD. How many slots are needed?
  4. Why does a triangle of clashes need three slots, whatever the rest of the graph?
  5. Why is the optimisation problem “fewest slots” no easier than the decision problem with s=3s = 3?

Part II — The gadgets.

  1. In the palette triangle, why can the names T, F and B be given to the colours after the colouring is found?
  2. Why is exactly one of xx, ¬x\neg x coloured T in any 3-colouring?
  3. In an OR gadget, show that if aa and bb are both F then the output is F.
  4. Show that if aa is T, the gadget can be coloured with output T, whatever bb is.
  5. Why must the second output of each clause be T?
  6. Why does a clause with three false literals make the graph uncolourable?

Part III — Sizes.

  1. Count the vertices: 2n+6m+32n + 6m + 3.
  2. Count the edges: 3n+12m+33n + 12m + 3.
  3. Check both counts against Output 17.4.
  4. A timetable instance built from a formula with 100 variables and 430 clauses: how many exams and clashes?
  5. Why is the reduction computable in polynomial time?
  6. What do the counts say about the size of the hard instances 3-colouring inherits from 3-SAT?

Part IV — Two slots against three.

  1. Show that a graph has a 2-colouring if and only if it has no cycle of odd length.
  2. Give a linear-time algorithm for two slots, and say what it returns when there is no timetable.
  3. Reduce 2-slot timetabling to 2-SAT: one variable per exam.
  4. Why does the same idea fail for three slots?
  5. The school has 40 exams and three slots. Does NP-completeness mean that its timetable cannot be found?
  6. What does a school with too many clashes for three slots learn from a failed search, and what would a certificate of impossibility look like?
  7. Sum up: what changes between two slots and three?
Solution

Solution of Problem 17.1.

1. Given a graph and ss, is there a map from vertices to {1,…,s}\{1, \ldots, s\} giving different values to the two ends of every edge?

2. The certificate is the timetable; checking looks at every vertex and edge once, O(n+m)O(n + m).

3. Three: ABC and DEF are triangles; A, B, C get three slots, D a slot other than C’s, E and F the other two.

4. Its three exams pairwise clash, so they need three different slots.

5. An algorithm for the fewest slots answers the decision with s=3s = 3 by comparing; so the optimisation is NP-hard too.

6. The three palette vertices are pairwise adjacent, so they take three different colours; calling those colours T, F and B is just naming them.

7. xx and ¬x\neg x are adjacent to B and to each other, so they take the two colours other than B’s, one each.

8. uu is adjacent to aa (F) and vv to bb (F), so u,v∈{T,B}u, v \in \{T, B\}, different from each other; the output is adjacent to both, so it is F.

9. Colour uu F (its neighbour aa is T), vv B (bb is T or F), the output T.

10. It is adjacent to F and B.

11. The first gadget’s output is F (question 8), and then the second gadget’s inputs are both F, so its output is F, but it must be T.

12. 3 palette vertices, 2n2n literal vertices, 6 per clause.

13. 3 palette edges, 3 per variable, 12 per clause: 5 per OR gadget and 2 to F and B.

14. n=3n = 3, m=2m = 2: 6+12+3=216 + 12 + 3 = 21 and 9+24+3=369 + 24 + 3 = 36, as printed.

15. 200+2,580+3=2,783200 + 2{,}580 + 3 = 2{,}783 exams and 300+5,160+3=5,463300 + 5{,}160 + 3 = 5{,}463 clashes.

16. It writes O(n+m)O(n + m) vertices and edges, each by a fixed rule.

17. They are linear: a formula of size NN becomes a graph of size O(N)O(N), so if 3-SAT needs time 2Ω(N)2^{\Omega(N)} in the worst case, so does 3-colouring, up to the constant in the exponent.

18. In a 2-colouring colours alternate along any walk, so a cycle has even length. Conversely, if there is no odd cycle, colour each component by the parity of the distance from a start vertex; an edge between two vertices of the same parity would close an odd cycle.

19. Breadth-first search, colouring each new vertex opposite to its parent; on an edge whose ends have the same colour, stop: the two paths to the start and that edge form an odd closed walk, which contains an odd cycle, the certificate that no timetable exists.

20. xvx_v means “exam vv in slot 1”; each clash uvuv gives (xu∨xv)(x_u \vee x_v) and (¬xu∨¬xv)(\neg x_u \vee \neg x_v): exactly one of the two in slot 1.

21. With three slots a vertex needs more than one Boolean variable, and “different slots” is no longer a conjunction of two-literal clauses: “at least one slot” needs three literals.

22. No. It means no known algorithm is fast on every graph; with 40 exams, backtracking or a SAT solver (Chapter 18) finds a timetable or proves there is none quickly in practice.

23. That a solver found no timetable, which is not a short certificate: proofs of non-colourability can be long, since 3-colouring’s complement is in co-NP and not known to be in NP. A small certificate exists in special cases, such as four pairwise clashing exams.

24. Two slots: linear time, by breadth-first search or 2-SAT, with an odd cycle as a short proof of impossibility. Three slots: NP-complete by the gadgets, with 2n+6m+32n + 6m + 3 vertices and 3n+12m+33n + 12m + 3 edges per formula; solved in practice by search, with no short proof of impossibility known in general.

本章定义的术语

在术语表中查看全部 1050 个术语