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

University Computer Science — Year 3

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

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

16Time and Space Complexity

Chapter 15 separated the problems that have a program from those that have none. Among the problems that do, some are solved in a fraction of a second on inputs of millions of items and others take longer than any computer can run once the input has a hundred. This chapter measures problems, not programs: it groups them into classes by the time or the space the best machine needs, and asks how the classes relate. Checking a proposed answer turns out to be easy for many problems whose search looks hard, which defines NP; a search can be built from a yes-or-no oracle; more time and more space provably give more power; and space behaves better than time: a nondeterministic search through a maze can be replaced by a deterministic one using only the square of its memory.

You already know

f=O(g)f = O(g) means f(n)≤c g(n)f(n) \le c\,g(n) for some constant cc and all large nn; a polynomial bound is O(nc)O(n^c) for a constant cc (Year 1 volume). Chapter 15 defined Turing machines with one or several tapes, and showed that one tape simulates kk with a quadratic slowdown. Backtracking explores the choices of a search one at a time, undoing each choice that leads nowhere, and may try exponentially many (Year 1 volume).

16.1 Classes of time and space

Definition 16.1 (Decision problem, instance size)

A decision problem is a set of instances, each with the answer yes or no; formally, the language of the encodings of the yes-instances. The instance size nn is the length of the encoding: a list of numbers takes the total number of their digits, a graph its number of vertices and edges, up to a constant factor.

The encoding matters only in one way: numbers must be written in a base of at least 2. Written in unary, the number NN takes NN symbols instead of about log⁡2N\log_2 N, and an algorithm that takes NN steps would look linear when it is exponential in the length of NN.

Definition 16.2 (Time complexity class, space complexity class, class P)

For a function ff, the time complexity class TIME(f)\mathrm{TIME}(f) is the set of decision problems decided by a multi-tape Turing machine in O(f(n))O(f(n)) steps on inputs of size nn. The space complexity class SPACE(f)\mathrm{SPACE}(f) is the set decided using O(f(n))O(f(n)) cells of work tapes, the input being on a read-only tape that does not count. The class P is ⋃cTIME(nc)\bigcup_c \mathrm{TIME}(n^c): the problems decidable in polynomial time.

P is robust: one tape simulates several with a quadratic slowdown (Theorem 15.4), and a random-access machine, or a Python program whose integers stay of polynomial size, is simulated by a Turing machine with a polynomial slowdown too. So whether a problem is in P does not depend on the model, while whether it is in TIME(n2)\mathrm{TIME}(n^2) does. Cobham and Edmonds proposed in 1965 to take P as the formal meaning of “feasibly computable”.

The time and space classes go back to Hartmanis and Stearns, and to Stearns, Hartmanis and Lewis, both in 1965.

16.2 P and NP

To decide whether some of the numbers 3,34,4,12,5,23, 34, 4, 12, 5, 2 add up to 99, a search may try all 64 subsets. To be convinced that they do, it is enough to be shown {4,5}\{4, 5\} and to add. Many problems share that shape: finding is hard, checking is easy.

Definition 16.3 (Certificate, verifier, class NP, nondeterministic Turing machine)

A verifier for a decision problem AA is an algorithm VV that takes an instance xx and a word cc, the certificate, such that xx is a yes-instance if and only if V(x,c)V(x, c) accepts for some cc. The class NP is the set of problems that have a verifier running in time polynomial in the size of xx (so only certificates of polynomial length matter). A nondeterministic Turing machine may have several transitions for the same state and symbol; it accepts when some sequence of choices leads to acceptance.

NP stands for “nondeterministic polynomial time”: a problem has a polynomial-time verifier if and only if a nondeterministic machine decides it in polynomial time, since the machine can guess the certificate one symbol per step, and conversely its choices form a certificate. P is contained in NP: a problem decided in polynomial time has the verifier that ignores the certificate. Whether the inclusion is strict is the question of Chapter 17.

verifiers.py checks certificates for subset sum (a set of indices), Hamiltonian path (an ordering of the vertices, each consecutive pair joined by an edge) and 3-colouring (a colour per vertex, different at the ends of each edge), and counts its steps.

def hamiltonian_path(n, edges, order):
    """Certificate: the vertices 0..n-1, each once, consecutive ones adjacent."""
    steps, adjacent = len(edges), set(edges) | {(v, u) for u, v in edges}
    if sorted(order) != list(range(n)):
        return False, steps + n
    for u, v in zip(order, order[1:]):
        steps += 1
        if (u, v) not in adjacent:
            return False, steps
    return True, steps


def three_colouring(n, edges, colour):
    """Certificate: a colour 0, 1 or 2 per vertex, the ends of each edge different."""
    steps = n
    if len(colour) != n or any(c not in (0, 1, 2) for c in colour):
        return False, steps
    for u, v in edges:
        steps += 1
        if colour[u] == colour[v]:
            return False, steps
    return True, steps
Listing 16.1. Two of the three verifiers. Each looks at every vertex and edge once. code/bachelor-3/16-complexity-classes/listings/verifiers.py
$ python verifiers.py
    n   subset sum   Hamiltonian path   3-colouring   (steps, all accepted)
   10            5                 29            30
  100           50                299           300
 1000          500               2999          3000
10000         5000              29999         30000
Output 16.1. Verification steps on graphs with nn vertices and 2n2n edges: linear in nn.

Without a certificate, the obvious algorithm for subset sum tries every subset. The program search_vs_verify.py builds all 2n2^n subset sums of nn even numbers, looking for an odd target that is never there; checking a certificate would take nn steps.

Searching against checking, for subset sum with no solution, on a logarithmic scale: from search_vs_verify.py. At n = 22 the search computes 4,194,304 sums.
Searching against checking, for subset sum with no solution, on a logarithmic scale: from search_vs_verify.py. At n=22n = 22 the search computes 4,194,304 sums.

An optimisation problem becomes a decision problem with a threshold: “what is the shortest tour?” becomes “is there a tour of length at most BB?”. If the decision is easy, so is the optimum, by binary search on BB (Exercise 16.2). The search for a solution, not only its value, also reduces to decisions.

Definition 16.4 (Self-reducibility)

A problem in NP is self-reducible when a certificate for a yes-instance can be found in polynomial time with the help of an oracle that answers the decision problem itself, each call counting as one step.

Theorem 16.5 (SAT is self-reducible)

Given an oracle that decides whether a Boolean formula in conjunctive normal form is satisfiable, a satisfying assignment of a satisfiable formula with nn variables can be found with n+1n + 1 calls.

Proof. One call checks that φ\varphi is satisfiable. Then, for i=1,…,ni = 1, \ldots, n: let φ1\varphi_1 be φ\varphi with xix_i set to true and simplified. If the oracle says φ1\varphi_1 is satisfiable, keep xi=x_i = true and continue with φ1\varphi_1. Otherwise every satisfying assignment of φ\varphi, and there is one by the invariant “the current formula is satisfiable”, has xi=x_i = false, so continue with φ\varphi with xix_i set to false, without asking. The invariant holds at every step, and after nn steps all variables are set and the formula is satisfied. ∎

def fix(clauses, i, value):
    """Set x_i: drop the satisfied clauses, remove the literal from the others. An
    emptied clause stays, as an empty clause, which no assignment satisfies."""
    lit = i if value else -i
    return [[x for x in c if x != -lit] for c in clauses if lit not in c]


def find_assignment(clauses, n):
    if not satisfiable(clauses, n):
        return None
    values = []
    for i in range(1, n + 1):
        trial = fix(clauses, i, True)
        if satisfiable(trial, n):  # keep x_i = True if the rest can still be satisfied
            clauses, value = trial, True
        else:  # otherwise x_i = False must work, since the formula was satisfiable
            clauses, value = fix(clauses, i, False), False
        values.append(value)
    return values
Listing 16.2. Finding an assignment with a yes-or-no oracle: one call per variable, plus one. code/bachelor-3/16-complexity-classes/listings/self_reduce.py
$ python self_reduce.py
n =  6, 24 clauses: satisfiable, 7 oracle calls, assignment checked: True
n =  8, 32 clauses: satisfiable, 9 oracle calls, assignment checked: True
n = 10, 40 clauses: satisfiable, 11 oracle calls, assignment checked: True
n = 12, 48 clauses: satisfiable, 13 oracle calls, assignment checked: True
n =  3, 8 clauses: None, 1 oracle call
Output 16.2. n+1n + 1 oracle calls when the formula is satisfiable, one when it is not.

The oracle here is an exhaustive search, but the algorithm uses only its answers: whatever the oracle costs, finding costs at most n+1n + 1 times as much as deciding.

16.3 The hierarchy theorems

More time should give more power. Hartmanis and Stearns proved it, by diagonalisation.

Theorem 16.6 (Time hierarchy theorem, space hierarchy theorem)

For a function ff computable in time ff itself, some problem is decided in time O(f(n)log⁡f(n))O(f(n) \log f(n)) but not in time o(f(n))o(f(n)). For a function f≥log⁡nf \ge \log n computable in space ff, some problem is decided in space O(f(n))O(f(n)) but not in space o(f(n))o(f(n)).

Proof idea. The machine DD, on input ⟨M⟩\langle M \rangle padded with symbols, simulates MM on its own input for f(n)f(n) steps and does the opposite of what MM answers. No machine MM running in time o(f)o(f) decides the same problem as DD: on long enough paddings of ⟨M⟩\langle M \rangle the simulation finishes and DD disagrees with MM. The factor log⁡f(n)\log f(n) pays for the simulation’s step counter and for moving MM’s description along the tapes; the space version needs no such factor. ∎

So TIME(na)\mathrm{TIME}(n^a) is strictly smaller than TIME(nb)\mathrm{TIME}(n^b) when a<ba < b, and P is strictly smaller than EXP, the class defined in Section 16.4 (Exercise 16.11).

The theorems separate classes of the same kind, time from time and space from space. They say nothing about P against NP, whose machines differ in kind.

16.4 Polynomial space

Definition 16.7 (EXP, PSPACE, TQBF)

EXP is ⋃cTIME(2nc)\bigcup_c \mathrm{TIME}(2^{n^c}) and PSPACE is ⋃cSPACE(nc)\bigcup_c \mathrm{SPACE}(n^c); NPSPACE is the same with nondeterministic machines. TQBF is the problem of deciding whether a fully quantified Boolean formula Q1x1 Q2x2⋯Qnxn φQ_1 x_1\, Q_2 x_2 \cdots Q_n x_n\, \varphi, each QiQ_i being ∃\exists or ∀\forall, is true.

Space can be reused and time cannot, so space is the more generous resource: a machine that runs for tt steps uses at most tt cells, and a machine that uses ss cells has at most 2O(s)2^{O(s)} configurations, so if it halts it does within that many steps. Hence P⊆PSPACE⊆EXP\mathrm{P} \subseteq \mathrm{PSPACE} \subseteq \mathrm{EXP}, and NP is inside PSPACE too (Exercise 16.8).

TQBF is a game. ∃x1 ∀x2 ∃x3…φ\exists x_1\, \forall x_2\, \exists x_3 \ldots \varphi says: the first player can choose x1x_1 so that whatever the second chooses for x2x_2, the first can choose x3x_3 so that …, and in the end φ\varphi holds. A recursion evaluates it in space proportional to nn, keeping only one branch at a time: the depth is nn, the time 2n2^n.

def value(quantifiers, phi, bits=()):
    """Evaluate Q1 x1 Q2 x2 ... phi(x): depth n, one branch stored at a time."""
    global calls
    calls += 1
    if len(bits) == len(quantifiers):
        return phi(bits)
    branches = (value(quantifiers, phi, bits + (b,)) for b in (False, True))
    return any(branches) if quantifiers[len(bits)] == "E" else all(branches)
Listing 16.3. Evaluating a quantified formula by recursion: any for ∃\exists, all for ∀\forall. code/bachelor-3/16-complexity-classes/listings/qbf.py
$ python qbf.py
 1 tokens: E            first player wins;     2 calls, depth 1
 2 tokens: EA           first player wins;     6 calls, depth 2
 3 tokens: EAE          second player wins;    11 calls, depth 3
 4 tokens: EAEA         first player wins;    12 calls, depth 4
 5 tokens: EAEAE        first player wins;    30 calls, depth 5
 6 tokens: EAEAEA       second player wins;    49 calls, depth 6
 7 tokens: EAEAEAE      first player wins;    50 calls, depth 7
 8 tokens: EAEAEAEA     first player wins;   126 calls, depth 8
 9 tokens: EAEAEAEAE    second player wins;   203 calls, depth 9
10 tokens: EAEAEAEAEA   first player wins;   204 calls, depth 10
11 tokens: EAEAEAEAEAE  first player wins;   502 calls, depth 11
12 tokens: EAEAEAEAEAEA second player wins;   801 calls, depth 12
Output 16.3. The game “take 1 or 2 tokens, whoever takes the last wins”: the second player wins exactly when mm is a multiple of 3.

TQBF is in PSPACE, and every problem in PSPACE reduces to it in polynomial time: it is complete for PSPACE, as Stockmeyer and Meyer showed in 1973.

16.4.1 Savitch’s theorem

Nondeterminism seems to buy exponential time; for space it buys at most a square. The key is reachability: is there a path from uu to vv in a graph of nn vertices? A nondeterministic machine walks, guessing each next vertex and remembering only the current one and a step counter: O(log⁡n)O(\log n) bits. Breadth-first search is deterministic but stores a set of up to nn visited vertices. Savitch’s algorithm stores neither.

Theorem 16.8 (Savitch’s theorem)

Reachability in a directed graph of nn vertices can be decided deterministically in space O(log⁡2n)O(\log^2 n). More generally, every problem decided by a nondeterministic machine in space f(n)≥log⁡nf(n) \ge \log n is decided by a deterministic machine in space O(f(n)2)O(f(n)^2); in particular NPSPACE == PSPACE.

Proof. Let R(u,v,k)R(u, v, k) say that a path of length at most 2k2^k leads from uu to vv. R(u,v,0)R(u, v, 0) holds when u=vu = v or (u,v)(u, v) is an edge. For k>0k > 0, R(u,v,k)R(u, v, k) holds if and only if there is a vertex ww with R(u,w,k−1)R(u, w, k - 1) and R(w,v,k−1)R(w, v, k - 1): cut the path in its middle. Compute RR by this recursion, trying w=1,…,nw = 1, \ldots, n and evaluating the two halves one after the other. A frame stores uu, vv, kk and ww, O(log⁡n)O(\log n) bits, and the recursion is k+1k + 1 frames deep. Paths need at most n−1n - 1 edges, so k=⌈log⁡2n⌉k = \lceil \log_2 n \rceil suffices: O(log⁡n)O(\log n) frames of O(log⁡n)O(\log n) bits. The general statement applies the same recursion to the graph of configurations of the nondeterministic machine, which has 2O(f(n))2^{O(f(n))} vertices, each written in O(f(n))O(f(n)) bits (Exercise 16.10). ∎

Walter Savitch published it in 1970.

Savitch’s recursion for paths of length at most 8: each node tries every midpoint, but only the current chain of calls from the root is in memory. The calls with k = 0, which only test for an edge, are not drawn.
Savitch’s recursion for paths of length at most 8: each node tries every midpoint, but only the current chain of calls from the root is in memory. The calls with k=0k = 0, which only test for an edge, are not drawn.
    def reach(self, u, v, k):
        self.calls += 1
        self.depth += 1
        self.max_depth = max(self.max_depth, self.depth)
        if k == 0:
            found = u == v or (u, v) in self.edges
        else:
            found = any(self.reach(u, w, k - 1) and self.reach(w, v, k - 1)
                        for w in range(self.n))
        self.depth -= 1
        return found

    def path_exists(self, u, v):
        return self.reach(u, v, max(1, math.ceil(math.log2(self.n))))
Listing 16.4. The midpoint recursion, with its calls and its depth counted. code/bachelor-3/16-complexity-classes/listings/savitch.py
$ python savitch.py
directed path 0 -> 1 -> ... -> n-1; from 0 to n-1, then back from n-1 to 0
  n   k   reachable  depth        calls   unreachable  depth        calls
  2   1        True      2            3         False      2            4
  4   2        True      3           20         False      3           31
  8   3        True      4          443         False      4          820
 16   4        True      5       47,038         False      5       88,741
town: 30 places, 53 roads (1 one-way), 105 directed edges
place 1 to place 30: True, depth 6, 1,858 calls; BFS visits 30 places
Output 16.4. The depth is k+1k + 1; the calls grow like nlog⁡2nn^{\log_2 n}. On the town’s road map BFS visits all 30 places.

The memory is tiny and the time is not: on 16 vertices the unreachable query makes 88,741 calls, about 216=16log⁡2162^{16} = 16^{\log_2 16}. Savitch’s algorithm is a statement about space, not a way to find a route; the weekend problem measures the trade-off.

16.5 Logarithmic space

Definition 16.9 (Class L, class NL, log-space reduction)

The class L is SPACE(log⁡n)\mathrm{SPACE}(\log n): a deterministic machine with a read-only input and a work tape of O(log⁡n)O(\log n) cells, enough for a constant number of counters and pointers into the input. The class NL is the same for nondeterministic machines. A log-space reduction is a many-one reduction computed by such a machine with a write-only output tape.

Reachability is in NL, by the guessing walk, and every problem in NL reduces to it in logarithmic space: it is complete for NL. Savitch’s theorem puts NL inside SPACE(log⁡2n)\mathrm{SPACE}(\log^2 n). The complement, “is there no path?”, seems to need a certificate as long as the whole set of reachable vertices, yet Immerman and Szelepcsényi showed independently in 1987 that it is in NL too: NL is closed under complement.

The known inclusions form a chain.

L ⊂eq NL ⊂eq P ⊂eq NP ⊂eq PSPACE ⊂eq EXP. The hierarchy theorems make NL PSPACE and P EXP; every other inclusion drawn might be an equality.
L⊆NL⊆P⊆NP⊆PSPACE⊆EXP\mathrm{L} \subseteq \mathrm{NL} \subseteq \mathrm{P} \subseteq \mathrm{NP} \subseteq \mathrm{PSPACE} \subseteq \mathrm{EXP}. The hierarchy theorems make NL≠PSPACE\mathrm{NL} \ne \mathrm{PSPACE} and P≠EXP\mathrm{P} \ne \mathrm{EXP}; every other inclusion drawn might be an equality.

16.6 Exercises

Exercise 16.1 ★

For each problem, say what a certificate is and how to check it in polynomial time: (a) the number NN is composite; (b) the graph has a cycle through every vertex; (c) the graph has kk vertices that are pairwise adjacent; (d) a partly filled grid of a puzzle can be completed by the rules.

Solution

Solution of Exercise 16.1.

(a) A factor dd with 1<d<N1 < d < N: one division, polynomial in the number of digits of NN. (b) The cycle, as an order of the vertices: check that each vertex appears once and that consecutive vertices, the last and the first included, are adjacent. (c) The kk vertices: check that they are distinct and that each of the k(k−1)/2k(k - 1)/2 pairs is an edge. (d) The completed grid: check that it extends the given entries and obeys every rule, each rule looking at a few cells.

Exercise 16.2 ★

The optimisation problem: given distances between nn towns, the length of the shortest tour visiting each once. Write the decision version with a threshold, and show that a polynomial-time algorithm for the decision version gives one for the optimum when distances are integers below 2322^{32}.

Solution

Solution of Exercise 16.2.

Decision version: given the distances and a number BB, is there a tour of length at most BB? A tour has nn legs below 2322^{32}, so its length lies in [0,n⋅232][0, n \cdot 2^{32}]. Binary search on BB over that interval finds the least BB with a yes answer, which is the optimum, in about 32+log⁡2n32 + \log_2 n calls; each call is polynomial, and so is the total.

Exercise 16.3 ★

How much work space, in bits, do these use on a list of nn numbers of at most bb bits? (a) Computing the maximum in one pass. (b) Checking that the list is sorted. (c) Sorting a copy. (d) Breadth-first search on a graph of nn vertices.

Solution

Solution of Exercise 16.3.

(a) O(b+log⁡n)O(b + \log n) bits: the current maximum and an index. (b) The same: the previous number and an index. (c) O(nb)O(nb) bits for the copy. (d) O(nlog⁡n)O(n \log n) bits: a queue of up to nn vertex numbers and nn bits for the visited set.

Exercise 16.4 ★

Predict the number of oracle calls of find_assignment on a satisfiable formula with 20 variables, on an unsatisfiable one, and on a satisfiable one in which every variable must be false.

Solution

Solution of Exercise 16.4.

21, 1 and 21. find_assignment asks once at the start, then once per variable whatever the answer; when every variable must be false, each of the 20 trials answers no and the second branch is taken without a call (test_self_reduction_uses_n_plus_one_calls_and_exercise_4).

Exercise 16.5 ★★

exercises/ex5_hampath.py has a Hamiltonian-path verifier that accepts the certificate 0, 1, 0, 1 on the path 0−1−2−30 - 1 - 2 - 3. Explain why and fix it.

Solution

Solution of Exercise 16.5.

The buggy verifier checks only that the certificate has nn entries and that consecutive entries are adjacent: 0, 1, 0, 1 has four entries and uses the edge 0−10 - 1 three times, but never visits 2 or 3. The fix requires the certificate to be a permutation of 0,…,n−10, \ldots, n - 1, sorted(order) == list(range(n)), as hamiltonian_path does.

Exercise 16.6 ★★

Write verify_clique(n, edges, k, chosen), a verifier for “the graph has a clique of kk vertices” running in O(m+k2)O(m + k^2) steps. It is tested against brute force on every small graph.

Solution

Solution of Exercise 16.6.

exercises/ex6_clique.py: reject unless chosen has kk distinct vertices of the graph; put both directions of every edge in a set, O(m)O(m); then look up each of the k(k−1)/2k(k - 1)/2 pairs, O(k2)O(k^2). The test is test_exercise_6_clique.

Exercise 16.7 ★★

Prove that 3-colouring is self-reducible: given an oracle for “is this graph 3-colourable?”, find a colouring with a polynomial number of calls. (Try joining two vertices by an edge, or merging them.)

Solution

Solution of Exercise 16.7.

Facts used: adding edges never makes a non-colourable graph colourable; a vertex adjacent to two vertices of a triangle must take the third one’s colour.

Add a triangle t0,t1,t2t_0, t_1, t_2 to GG; the new graph is 3-colourable exactly when GG is, and in any colouring the triangle uses all three colours. For each vertex vv in turn, and for c=0,1c = 0, 1: join vv to the two triangle vertices other than tct_c, and ask the oracle; if it says yes, keep the edges and go to the next vertex, otherwise remove them. If neither c=0c = 0 nor c=1c = 1 works, join vv to t0t_0 and t1t_1 without asking: since the graph was colourable before, some colouring gives vv one of the three triangle colours, and it was not that of t0t_0 or t1t_1. The invariant “the current graph is 3-colourable” holds throughout, at most 2n+12n + 1 calls are made, and at the end each vv is forced to the colour of one triangle vertex: reading these gives a 3-colouring of GG.

Exercise 16.8 ★★

Prove NP⊆PSPACE\mathrm{NP} \subseteq \mathrm{PSPACE}.

Solution

Solution of Exercise 16.8.

Let VV be a verifier for AA running in time p(n)p(n); it reads at most p(n)p(n) symbols of the certificate. On xx, enumerate the certificates of length at most p(n)p(n) one after the other, in one buffer of p(n)p(n) cells, run V(x,c)V(x, c) on each, reusing its space, and accept if one is accepted. The space is O(p(n))O(p(n)) for the buffer plus O(p(n))O(p(n)) for a run of VV, which cannot use more cells than steps: polynomial. The time is exponential, which does not matter.

Exercise 16.9 ★★

Bound the number of calls of reach(u, v, k) on a graph of nn vertices, and compare with Output 16.4. Why does the reachable query make fewer calls than the unreachable one?

Solution

Solution of Exercise 16.9.

A call with k>0k > 0 makes at most 2n2n calls with k−1k - 1, two per midpoint, so C(k)≤1+2n C(k−1)C(k) \le 1 + 2n\,C(k - 1) with C(0)=1C(0) = 1, and C(k)≤(2n+1)kC(k) \le (2n + 1)^k. For n=16n = 16, k=4k = 4: 334=1,185,92133^4 = 1{,}185{,}921, against 88,741 printed for the unreachable query. The reachable query stops at the first midpoint that works, since any stops at the first true; and on either query and skips the second half when the first is false. On the unreachable query no midpoint works, so every midpoint is tried at every level.

Exercise 16.10 ★★★

Complete the proof of Savitch’s theorem: a nondeterministic machine using space f(n)≥log⁡nf(n) \ge \log n is simulated deterministically in space O(f(n)2)O(f(n)^2). Say what the vertices and edges of the configuration graph are, how many there are, and how the simulation reads an edge without storing the graph.

Solution

Solution of Exercise 16.10.

Facts used: the input is on a read-only tape and does not count; f(n)≥log⁡nf(n) \ge \log n.

A configuration of the machine on xx is its state, the position of the input head (O(log⁡n)O(\log n) bits), the position of the work head (O(log⁡f(n))O(\log f(n)) bits) and the work tape (O(f(n))O(f(n)) symbols): O(f(n))O(f(n)) bits, so there are N=2O(f(n))N = 2^{O(f(n))} configurations. The configuration graph has an edge c→c′c \to c' when one step leads from cc to c′c'; whether it does is decided by looking at the transition table and at the input symbol under cc’s input head, in space O(f(n))O(f(n)), without storing the graph. Make the machine erase its tape and move its heads home before accepting, so that there is one accepting configuration caccc_{\mathrm{acc}}. The machine accepts xx if and only if caccc_{\mathrm{acc}} is reachable from the start configuration, and Savitch’s recursion with k=⌈log⁡2N⌉=O(f(n))k = \lceil \log_2 N \rceil = O(f(n)) decides it with k+1k + 1 frames of O(f(n))O(f(n)) bits: O(f(n)2)O(f(n)^2). Computing kk requires ff to be computable in space ff, or trying k=1,2,…k = 1, 2, \ldots in turn.

Exercise 16.11 ★★★

Prove P≠EXP\mathrm{P} \ne \mathrm{EXP} from the time hierarchy theorem.

Solution

Solution of Exercise 16.11.

Take f(n)=2nf(n) = 2^n. The time hierarchy theorem gives a problem AA decided in time O(2n⋅n)O(2^n \cdot n), so A∈TIME(2n2)⊆EXPA \in \mathrm{TIME}(2^{n^2}) \subseteq \mathrm{EXP}, but in no time o(2n)o(2^n). Every problem in P is in TIME(nc)\mathrm{TIME}(n^c) for some cc, and nc=o(2n)n^c = o(2^n). So AA is not in P: P≠EXP\mathrm{P} \ne \mathrm{EXP}.

Exercise 16.12 ★★★

A graph is 2-colourable if and only if it has no cycle of odd length. Write two_colourable(n, edges) that stores no list or set, only a few vertex numbers per recursive call, by running Savitch’s recursion on the graph whose vertices are pairs (vertex, parity of the walk so far). What space does it use? It is tested against breadth-first colouring on random graphs.

Solution

Solution of Exercise 16.12.

exercises/ex12_bipartite.py. A walk from vv back to vv of odd length exists if and only if the graph has an odd cycle, since an odd closed walk contains an odd cycle; so the graph is 2-colourable if and only if no (v,0)(v, 0) reaches (v,1)(v, 1) in the parity graph. That graph has 2n2n vertices, and an edge (x,p)→(y,1−p)(x, p) \to (y, 1 - p) for each edge xyxy; the function adjacent reads it from the edge set without building it. The recursion is ⌈log⁡22n⌉+1\lceil \log_2 2n \rceil + 1 frames deep, each holding six small numbers, O(log⁡n)O(\log n) bits: O(log⁡2n)O(\log^2 n) space, the input aside (test_exercise_12_bipartite).

16.7 Weekend problem

Problem 16.1

Weekend problem — Savitch in the maze

Brenmoor’s road map has 30 places and 53 roads, one of them one-way. This problem compares two ways of deciding whether one place can be reached from another: breadth-first search, fast but with a memory that grows with the map, and Savitch’s recursion, which remembers almost nothing and pays for it in time. The counts are those of Output 16.4.

Part I — Breadth-first search.

  1. How many steps does BFS take on a graph of nn vertices and mm edges? Count them for the town, with each two-way road as two directed edges.
  2. How much memory does BFS use, in vertices and in bits, when every place is reachable?
  3. Why can BFS not do with less, when it must remember which places it has seen?
  4. Depth-first search uses a stack instead of a queue. Is its memory smaller in the worst case?
  5. With n=109n = 10^9 vertices, how much memory does BFS need, at 4 bytes per vertex?

Part II — The midpoint recursion.

  1. What kk does path_exists use for the town, and why is it enough?
  2. What does one frame store, and how many bits does it need for 30 places?
  3. Check the printed depth for the town against k+1k + 1.
  4. Bound the total memory in bits, and compare with BFS.
  5. For n=109n = 10^9, how many frames and how many bytes does the recursion need?
  6. Why does the recursion evaluate the two halves one after the other rather than both at once?

Part III — What it costs.

  1. Write a recurrence for the number of calls C(k)C(k) on the unreachable query, in the worst case.
  2. Solve it: show C(k)≤(2n+1)kC(k) \le (2n + 1)^k.
  3. Compute log⁡2\log_2 of the printed calls of the unreachable query for n=4,8,16n = 4, 8, 16 and compare with (log⁡2n)2(\log_2 n)^2.
  4. From that fit, predict the calls for n=32n = 32 and n=1,024n = 1{,}024. How long would n=32n = 32 take at a million calls per second?
  5. Why is the time nO(log⁡n)n^{O(\log n)}, more than any polynomial but less than 2n2^n?
  6. The town’s query made only 1,858 calls with 30 places. Why so few?

Part IV — The trade-off.

  1. Which would you run on the town, and which on a graph given only as a function that returns the neighbours of a vertex, too large to store?
  2. Can a deterministic algorithm use O(log⁡n)O(\log n) space and polynomial time for reachability in directed graphs? What would that say about L and NL?
  3. Why does nondeterminism make reachability easy in O(log⁡n)O(\log n) space?
  4. Savitch’s theorem gives NL⊆SPACE(log⁡2n)\mathrm{NL} \subseteq \mathrm{SPACE}(\log^2 n). Why is the corresponding statement for time, NP inside a small power of P, not known?
  5. Explain how the configuration graph of a machine turns any space-bounded computation into a maze.
  6. Why does the result imply NPSPACE=PSPACE\mathrm{NPSPACE} = \mathrm{PSPACE}?
  7. Sum up: what does each method spend, and what does it save?
Solution

Solution of Problem 16.1.

1. O(n+m)O(n + m): each vertex enters the queue once and each edge is looked at once. For the town, 30 places and 105 directed edges: about 135 steps.

2. A visited set of 30 places and a queue of at most 30: about 60 numbers of 5 bits, 300 bits; with the visited set as one bit per place, 30 bits plus the queue.

3. BFS must not visit a place twice, and in the worst case any place seen may come back; it keeps the whole frontier and the set of places seen, which grow with the map.

4. No: on a path the stack holds all nn vertices.

5. 4 GB for the queue in the worst case, plus 125 MB for a visited bitmap.

6. k=⌈log⁡230⌉=5k = \lceil \log_2 30 \rceil = 5: a path between two places has at most 29 roads, fewer than 25=322^5 = 32.

7. uu, vv, ww (5 bits each for 30 places) and kk (3 bits): 18 bits.

8. 5+1=65 + 1 = 6, as printed.

9. 6×18=1086 \times 18 = 108 bits, against about 300 for BFS. Small maps hide the difference: O(log⁡2n)O(\log^2 n) against O(nlog⁡n)O(n \log n).

10. k=30k = 30, 31 frames of 30+30+30+5=9530 + 30 + 30 + 5 = 95 bits: about 2,950 bits, under 400 bytes, against gigabytes.

11. The second half reuses the memory of the first; evaluating both at once would double the memory at every level and make it linear in nn again.

12. C(0)=1C(0) = 1 and C(k)≤1+2n C(k−1)C(k) \le 1 + 2n\,C(k - 1): each of nn midpoints may need two calls.

13. By induction: 1+2n(2n+1)k−1≤(2n+1)k−1+2n(2n+1)k−1=(2n+1)k1 + 2n(2n + 1)^{k - 1} \le (2n + 1)^{k - 1} + 2n(2n + 1)^{k - 1} = (2n + 1)^k.

14. log⁡231≈4.95\log_2 31 \approx 4.95, log⁡2820≈9.68\log_2 820 \approx 9.68, log⁡288,741≈16.44\log_2 88{,}741 \approx 16.44, against 4, 9 and 16: log⁡2C≈(log⁡2n)2+0.5\log_2 C \approx (\log_2 n)^2 + 0.5, so C≈1.4 nlog⁡2nC \approx 1.4 \, n^{\log_2 n}.

15. n=32n = 32: 225.5≈4.5×1072^{25.5} \approx 4.5 \times 10^7 calls, about 45 seconds. n=1,024n = 1{,}024: 2100.5≈1.8×10302^{100.5} \approx 1.8 \times 10^{30} calls, far longer than the age of the universe.

16. nlog⁡2n=2(log⁡2n)2n^{\log_2 n} = 2^{(\log_2 n)^2}: the exponent (log⁡2n)2(\log_2 n)^2 outgrows every clog⁡2nc \log_2 n, so no polynomial bounds it, and stays below nn, so it is less than 2n2^n.

17. The place is reachable, and any stops at the first midpoint that works. Midpoint uu itself works at once for the first half, R(u,u,k−1)R(u, u, k - 1), so the recursion soon reduces to shorter questions; the expensive case is a query that fails.

18. BFS on the town: it is fast and its memory is tiny anyway. A Savitch-style recursion only where memory is the constraint and the graph is given implicitly, by a function returning neighbours.

19. Nobody knows. Directed reachability is complete for NL under log-space reductions, so such an algorithm would give L=NL\mathrm{L} = \mathrm{NL}.

20. A nondeterministic walk guesses the next vertex at each step and keeps only the current vertex and a counter up to nn: O(log⁡n)O(\log n) bits.

21. Space can be reused: Savitch’s two halves share the same cells. Time cannot: a deterministic simulation of a guessing machine seems to need to try the guesses one after the other, and the only known bound is exponential, NP⊆EXP\mathrm{NP} \subseteq \mathrm{EXP}.

22. Its vertices are the configurations, its edges the single steps; the machine accepts if and only if a path leads from the start to the accepting configuration. A machine using space ss gives a maze of 2O(s)2^{O(s)} rooms.

23. A nondeterministic machine using space ncn^c is simulated deterministically in space n2cn^{2c}, still polynomial: NPSPACE⊆PSPACE\mathrm{NPSPACE} \subseteq \mathrm{PSPACE}, and the other inclusion is immediate.

24. BFS spends memory proportional to the graph and saves time, O(n+m)O(n + m); Savitch’s recursion spends time, nO(log⁡n)n^{O(\log n)}, and saves memory, O(log⁡2n)O(\log^2 n) bits. On the town both answer at once; the theorem matters when the graph is a configuration graph, far too large to store.

本章定义的术语

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