P, NP and the Cook-Levin theorem
NP-completeness theory explains why thousands of important problems resist efficient solution. Define decision, search and optimization problems, P and NP through verifiers, polynomial reductions and NP-completeness. Prove Cook–Levin by encoding a Turing machine execution as a formula, and study coNP and the self-reducibility converting decision into search.
After this lesson you can
- Formulate a problem as a decision language and relate it to search and optimization versions.
- Prove a problem belongs to NP by giving a certificate and polynomial verifier.
- Construct polynomial reductions and use them in the correct direction.
- Prove Cook–Levin with the configuration-tableau construction.
- Explain coNP, the NP = coNP question and obtaining solutions from a decision oracle.
Before you start
Motivation: finding versus checking
You have spent twenty-six lessons designing algorithms: sorting, matching, routing flow, finding paths. This lesson asks the opposite: how can we prove that an efficient algorithm for a problem will not be found? Nobody knows how to prove a natural problem requires superpolynomial time, but something almost as useful is possible: prove it is as hard as thousands of others resisting decades of attempts, so an efficient algorithm for it would solve them all. This guides work toward approximations, special cases, small parameters or a SAT solver instead of searching endlessly for a perfect exact algorithm.
Three real situations end up in the same family:
- Traveling salesperson. A courier visits 20 cities and returns to the depot. There are tours; at tours per second, checking all takes about two years. Bellman and Held–Karp dynamic programming (1962) reduces this to , a huge improvement still exponential. No polynomial algorithm is known.
- Shift scheduling. Is there an assignment of people to shifts respecting contracts, holidays, minimum rest and preferences? This is constraint satisfaction. With a few dozen people, the assignment space is astronomical.
- Exact program analysis. “Is there an input causing this assertion to fail within at most execution steps?” translates into a Boolean formula satisfiable exactly when such an input exists. This is precisely the idea proved below and used by bounded model checkers (see SAT in practice and SMT in the classical AI module).
All three share an asymmetry. Checking a proposal is easy: given a tour, sum 20 distances; given a schedule, check rules; given an input, execute the program. Finding the proposal seems to require exploring an exponential space. Whether this difference is real or merely lack of ingenuity is the versus question, one of the Clay Institute’s seven Millennium Problems, still open.
Explore the asymmetry before formalizing it. Choose a problem, propose a certificate and see checking cost; then let brute force search and increase size.
Three observations about what you just saw, and a caveat.
- Verification is one pass through the certificate. Subset sum takes steps, coloring one check per edge, and Sudoku one read per group. This grows as a small polynomial of input size.
- Brute force multiplies by a constant per unit of size: subsets, colorings, fillings of empty cells. Each extra number, vertex or cell doubles, triples or quadruples work.
- Candidates tried vary greatly depending on where the first solution lies in traversal order. Worst case does not.
The caveat: brute force is not the best known algorithm. Subset sum takes with meet-in-the-middle (Horowitz and Sahni, 1974), 3-coloring (Beigel and Eppstein, 2005), and Sudoku solves in milliseconds with backtracking and propagation. But all known algorithms for these problems remain exponential in the worst case, and for this lesson’s problems there is a structural reason, not just lack of ingenuity: they are equivalent to one another.
To turn intuition into mathematics fix three things: what a problem is, what efficient means and what checking means. Then compare problem difficulty with reductions and find the hardest efficiently verifiable problem (Cook and Levin).
Decision, search and optimization problems
Almost every computational problem has three versions. For clique, given a graph and seeking pairwise adjacent vertices:
- Decision. Given and , does have a clique of size at least ? Answer yes or no.
- Search. Given and , return a clique of size at least if one exists.
- Optimization. Given , return a maximum clique.
| Problem | Decision | Search | Optimization |
|---|---|---|---|
| Traveling salesperson | is there a tour of length ? | the tour | shortest tour |
| Satisfiability | is there an assignment satisfying ? | the assignment | one satisfying most clauses (MAX-SAT) |
| Subset sum | does some subset sum to ? | the subset | closest to without exceeding it |
| Coloring | can it be colored with colors? | the coloring | minimum color count |
Complexity theory usually formulates the first version because it is simplest: a function from to .
The rest concerns languages; do we lose anything ignoring search and optimization? Almost nothing, proved in two halves: optimization reduces to decision by binary-searching a threshold (now), and search reduces to decision by testing variables one by one (at the end).
Proof
Maintain interval containing , initially . While , ask about . If yes, and move to ; if no, and move to . Either way integer count becomes at most . Starting from , after steps remains, i.e. .
∎For maximum clique on 100 vertices, lies between 1 and 100 and queries suffice. The important condition is “integer bounded by ”: in traveling salesperson, optimum sums distances and has as many bits as distances themselves, so binary search makes polynomially many queries even with exponentially many tours. Implement it in the second code-section cell.
Size means bit count
“Polynomial in input size” matters only if size is measured correctly. An encoding is reasonable if two reasonable encodings of one instance have polynomially related sizes: an adjacency matrix takes bits and a vertex–edge list , and since sizes are polynomially related; either works. The classic trap is numbers. Writing in binary takes bits; in unary, . An -step algorithm is linear for unary input and exponential for binary.
Familiar examples: knapsack and subset-sum dynamic programming (pseudopolynomial algorithms) takes for numbers and target , but is exponential in its bit count: with 64-bit the table has order cells. It is pseudopolynomial because it is polynomial in numeric values, not their sizes. And testing primality by dividing by every integer up to takes steps, with the bit count of .
Class P
Choosing polynomial rather than, say, has technical and practical reasons.
Closure. Polynomials are closed under sum, product and composition. Running a polynomial algorithm polynomially many times, or feeding it another’s output, stays polynomial. Without this property there would be no reduction theory.
Model robustness. A single-tape Turing machine simulates a multitape one with quadratic overhead, and a RAM with logarithmic operation cost with polynomial overhead; thus is unchanged across reasonable models. This is the resource version of the Church–Turing thesis (called the strong thesis, viewed cautiously due to quantum computing: is not known to lie in ). This robustness lets the lesson say “polynomial time” without specifying a machine.
A practical warning: does not mean fast. An algorithm is in and useless; an algorithm is outside it and excellent for . The thesis says the polynomial–exponential boundary best survives model changes; experience says that, with few exceptions, problems solvable in eventually acquire small-exponent algorithms.
You have seen many members of : shortest paths, minimum spanning trees, maximum flow and matching. Also 2-SAT (strongly connected components, as in DFS), linear programming (Khachiyan, 1979) and, since 2002, primality (Agrawal, Kayal and Saxena).
Class NP
Look again at the first figure’s verifier: read a certificate and decide. That is the definition.
Notice two asymmetries. A short certificate is required only for positive instances: yes can be shown with a short proof, no need not be. And the verifier need not know how was found; the definition says nothing about finding difficulty.
| Problem | Certificate | Verifier checks |
|---|---|---|
| SAT | a variable assignment | every clause has a true literal |
| Clique of size | the vertices | each pair is an edge |
| Hamiltonian cycle | a permutation of vertices | consecutive pairs and last with first are edges |
| Subset sum | selected indices | their values sum to |
| 3-coloring | one color per vertex | no edge is monochromatic |
| Composite | a divisor with | |
| Sudoku | digits for empty cells | each group contains digits without repetition |
The name comes from another equivalent definition used by Cook and Karp. A nondeterministic Turing machine may choose among transitions at each step; it accepts if any computation branch accepts, and its time is that of the longest branch.
Proof
() Given verifier and polynomial , nondeterministic machine writes an -bit string bit by bit (two choices per bit, steps), then executes . A branch accepts iff some has , and time is polynomial.
() Let be nondeterministic with time . Assume it chooses at most two transitions per step (a choice among splits into binary choices). A certificate is the binary choices of a branch. The verifier simulates using those choices and accepts if the branch ends in an accepting state. It takes steps of , and accepts iff some choice sequence leads to acceptance.
∎The proof shows “nondeterministic” and “certificate” are the same idea in two disguises: nondeterminism guesses the certificate, and choosing an accepting branch is the certificate. It also explains the name: is nondeterministic polynomial time, not “non-polynomial.”
Proof
: if , verifier ignores and runs the algorithm deciding on . : given the verifier and , enumerate the possible certificates and run on each; accept if any accepts. This is polynomial-algorithm executions.
∎The time hierarchy theorem (Hartmanis and Stearns, 1965) shows , so at least one of the two inclusions is strict. Nobody knows which. asks, fundamentally, whether finding is essentially as easy as checking.
Polynomial reductions
How compare two problems’ difficulty without knowing how to solve either? Transform one into the other. If every instance can be converted in polynomial time into a instance with the same answer, any way to solve solves .
Reductions operate in one direction, easy to reverse accidentally.
Proof
Prove (3); parts (1) and (2) are a final guided exercise. Let verify and reduce to . A verifier for receives , computes and runs . Correctness follows from . It is polynomial because is polynomial-time and, as a machine writes at most one symbol per step, is polynomial in ; certificate remains polynomial in and hence .
∎The key is the contrapositive of (2): reduction transfers hardness from to , and easiness from to . Never the reverse. To prove a new problem hard, reduce a known hard problem to it.
Two qualifications. First, a more permissive Cook or Turing reduction: if a polynomial algorithm for may make polynomially many queries to a oracle and use answers arbitrarily, including negating them. Every Karp reduction is a Cook reduction (one query, unchanged answer). Cook formulated his 1971 result with oracle reductions; the Karp-reduction statement and 21-problem list are Karp (1972), while Levin proved it independently in the Soviet Union (published 1973). This distinction matters for : under Cook reduction SAT’s complement reduces to SAT (ask and negate), but that does not put it in , and a Karp reduction cannot negate the answer. Second, valid reductions require both implications: positive instances must yield positive instances and negative must yield negative.
NP-hardness and NP-completeness
NP-complete problems are the hardest in : every verifiable problem reduces to them. The halting problem is NP-hard (every language of reduces to it) but not NP-complete because it is undecidable and thus outside . Someone “having a reduction from to ” says something about only if is hard.
Proof
Let be NP-complete and . For any , , and by part (2) of the previous theorem, . Thus , and the other inclusion was already known. The second sentence is the contrapositive.
∎This gives the practical recipe, developed in the next lesson. To show NP-complete:
- : describe a polynomial-length certificate and polynomial verifier.
- Pick a problem already known NP-complete (or NP-hard).
- Construct polynomial-time function mapping instances to instances.
- Prove , both directions.
Step 2 works because reduction is transitive: if every reduces to and , every reduces to . But the recipe needs a first NP-complete problem, requiring reduction of all problems at once without knowing them. Cook and independently Levin achieved this.
The Cook–Levin theorem
SAT is in immediately: the certificate is an assignment and evaluating CNF is linear in size. Hardness is difficult: for any , construct in polynomial time from a CNF satisfiable iff .
The idea is that a computation is a table and a table is correct iff each small fragment is correct. Take verifier for with time and -bit certificates (padding with a marker makes lengths equal). One Boolean variable for each possible cell content in the configuration tableau, and clauses saying successive rows are legal steps and the certificate is the only free part.
The computation tableau
Fix as a deterministic single-tape Turing machine, tape infinite both ways, tape alphabet (blank ), states (including , accepting and rejecting , both halting) and transition . A configuration is tape content, head position and state, written as a row where each cell contains a symbol from or a head, a pair meaning “head here, in state , reading .” Cell alphabet is , and a row is a configuration if exactly one cell has a head. A halting configuration transitions to itself, so computation can extend to steps.
The tableau has rows (row is the configuration after steps) and columns: the head starts cells from the left edge and cannot leave the table in steps. Cells outside are treated as blanks.
The property enabling the construction is locality. With the head marked in its cell, a cell’s content at time depends only on the three cells above.
Proof
Define by cases. If is a nonhalting head, with , the head leaves that cell and writes : . If halts, . If and is a nonhalting head with , the head arrives at this cell: . If is a nonhalting head moving , the symmetric case gives . Otherwise the cell is unchanged: . One step changes only the head cell and one neighbor; these cases cover exactly those possibilities, so successor equals cell by cell. ( values on triples with two heads are arbitrary because they never occur in a configuration.)
∎Call the window of cell , with , the -cell block formed by the three above, , and the central one below, . It is legal if . Fixing the upper row determines the lower (not conversely: two configurations can have the same successor), enabling the next figure: a tiny screen-sized machine accepting three-bit certificates without consecutive ones.
The formula
Variables are for , and : “cell contains symbol .” There are variables, and since depends only on and can be taken (so ), there are . Formula has four parts.
Cells. Each cell has exactly one symbol:
Start. Row 0 is the initial configuration with input : blanks to the left, head in state on the first symbol of , fixed symbols of (one unit clause each), and in the certificate cells a free bit: one clause per cell (the head cell, if on , is ), with blanks to the right. Those cells are the formula’s only free variables: lives here.
Movement. For every cell with and every triple , a four-literal clause:
It says: if is above, below is what dictates. Together with (exactly one symbol below), this means the window is legal. At boundary columns omit the literal for the nonexistent cell.
Acceptance. Computation ends accepting: , one clause.
The proof
Proof
SAT . A certificate is an assignment and evaluating CNF is linear in its size.
SAT is NP-hard. Let have verifier , polynomials (certificate) and (time), and input . Compute as above. Show satisfiable iff .
() If , a certificate exists with and computation accepts in steps. Its tableau (with final configuration repeated through row ) gives an assignment: iff cell contains . It satisfies (one symbol per cell), (row 0 is the initial configuration on ), (by locality: each lower cell is of the three above) and (last row contains ).
() Let satisfy . By , describes a symbol tableau. By , row 0 is the initial configuration on , with the bits assigns to certificate cells. Induct on : if row is configuration , clauses say row is applied cellwise to , which by locality is successor (every triple occurring in has at most one head, so arbitrary values of do not matter). Thus the table is ’s computation on . By row contains , so accepts and .
The reduction is polynomial. has clauses, which are since is a constant depending on not ; each is written in constant time by consulting . Only input-symbol clauses depend on . Since and are polynomials in , computation is polynomial.
∎For the figure’s machine (; since the head moves only right and halts within four steps, columns suffice rather than in the general bound; fifteen cell symbols), the formula has 630 variables and 91 085 clauses, or 14 045 if only triples with at most one head are written, the only ones possible. In code you will build it and use a SAT solver from scratch to check its models are exactly the five certificates accepted by the machine.
What it does and does not say
The reduction is universal: it depends not on which problem is, only its verifier. And it preserves certificates: a satisfying assignment of contains certificate in free row-0 cells (and conversely). This later converts decision to search. Quadratic size can be improved: simulating a machine whose head always moves the same way (Pippenger and Fischer, 1979) needs only . Alternatively, construct a Boolean circuit simulating the machine and use the Tseitin transformation to obtain an equisatisfiable linear-size CNF: another route to the same result.
What it does not say: SAT is not proven intractable (we do not know whether ), nor is the construction necessarily practical (constants are huge: 91 085 clauses for a five-step machine and three bits). It says that a polynomial SAT algorithm would solve all problems in polynomial time; and meanwhile, proving a problem NP-complete proves it is equivalent to SAT.
coNP and the missing symmetry
The definition of is asymmetric: yes has a short certificate, no need not. Reversing that asymmetry gives another class.
Examples: tautology (is a formula true under every assignment?), whose no has a short certificate, a falsifying assignment; unsatisfiability (UNSAT), SAT’s complement; and non-Hamiltonian, Hamiltonian cycle’s complement. By definition the complement of an problem lies in . No short certificate is known for nonexistence of a Hamiltonian cycle or unsatisfiability, and conjecturally none exists.
Two facts relate these classes to the above.
- because is closed under complement: flip the answer.
- If , then , for the same reason. Thus conjecture is stronger than .
Proof
Let . Since is NP-complete, exists with , i.e. . Since , , and by part (3) of the reductions theorem, , i.e. . Thus . Taking complements gives .
∎This has two effects: no problem can be NP-complete unless . And problems there that appear hard but have short certificates of both kinds signal they are probably not NP-complete.
From decision to search
The other promised half: do we lose anything by deciding instead of searching? For natural problems, no. Suppose a black box says whether a formula is satisfiable but gives no assignment. Find one by testing variables one by one.
Proof
First ask whether is satisfiable; stop if not. Maintain invariant “the current formula is satisfiable.” For : substitute into the current formula (delete clauses containing literal and remove from the rest) and ask if the result is satisfiable. If yes, set . If no, since current formula was satisfiable but not with , it is with : set without asking. Either way the resulting formula is satisfiable with one fewer variable. After steps all variables are fixed and the assignment satisfies . There were calls, each on a formula no larger than .
∎The same idea works for clique: if has a size- clique, traverse vertices and delete if the graph without still has a clique of size . Each remaining vertex is essential, so remaining vertices form exactly a clique of size . This is an exercise activity.
For arbitrary problems there is no universal way to delete or fix variables, but none is needed: Cook–Levin covers everything. Reduction from to SAT preserves certificates, so obtain an certificate by reading free row-0 cells in a satisfying assignment of found by self-reducibility. Thus if , not only deciding but finding solutions to every problem would be polynomial. Another reason to believe : the opposite world would permit finding proofs of every theorem with a short proof.
Between and NP-complete problems
If , is every problem either polynomial or NP-complete? No. Ladner’s theorem (1975): if , languages in exist outside that are not NP-complete (NP-intermediate problems). The proof diagonalizes against all polynomial algorithms and all reductions simultaneously, producing an artificial language. Natural candidates include factoring and graph isomorphism; Babai (2016) gave a quasipolynomial algorithm for the latter, making NP-completeness less plausible.
Implementation from scratch
Four cells in order, then a final experiment. First write verifiers and measure their steps; second, a SAT solver and assignment search using only a decision oracle; third, the tiny machine’s Cook–Levin formula and a custom solver to check it; fourth, maximum clique by binary search checked against networkx.
import random
def verifica_sat(cnf, asignacion):
"""cnf: lista de cláusulas (listas de enteros no nulos: v o -v). asignacion[v]: bool. Devuelve (ok, pasos)."""
pasos = 0
for clausula in cnf:
satisfecha = False
for lit in clausula:
pasos += 1
if asignacion[abs(lit)] == (lit > 0):
satisfecha = True
break
if not satisfecha:
return False, pasos
return True, pasos
def verifica_clique(aristas, S):
E = {frozenset(e) for e in aristas}
S, pasos = list(S), 0
for i in range(len(S)):
for j in range(i + 1, len(S)):
pasos += 1
if frozenset((S[i], S[j])) not in E:
return False, pasos
return True, pasos
def verifica_suma(nums, objetivo, indices):
indices = set(indices)
return sum(nums[i] for i in indices) == objetivo, len(indices)
def sat_plantado(n, m, rng):
"""3-CNF con n variables y m cláusulas que satisface una asignación elegida de antemano."""
sol = {v: rng.random() < 0.5 for v in range(1, n + 1)}
cnf = []
while len(cnf) < m:
vs = rng.sample(range(1, n + 1), 3)
c = [v if rng.random() < 0.5 else -v for v in vs]
if any(sol[abs(l)] == (l > 0) for l in c):
cnf.append(c)
return cnf, sol
rng = random.Random(1)
print(" n m ok pasos pasos/(3m)")
for n in (100, 200, 400, 800):
cnf, sol = sat_plantado(n, 4 * n, rng)
ok, pasos = verifica_sat(cnf, sol)
print(f"{n:4d} {4*n:5d} {ok} {pasos:6d} {pasos / (3 * 4 * n):.3f}")
# un clique de tamaño 12 en un grafo aleatorio de 60 vértices, y un certificado falso
aristas = [(i, j) for i in range(60) for j in range(i + 1, 60) if rng.random() < 0.3]
S = list(range(12))
aristas += [(i, j) for i in S for j in S if i < j]
print("clique verdadero:", verifica_clique(aristas, S), " certificado falso:", verifica_clique(aristas, list(range(5, 17))))
nums = [rng.randrange(10**6, 10**7) for _ in range(30)]
idx = rng.sample(range(30), 8)
print("suma de subconjuntos:", verifica_suma(nums, sum(nums[i] for i in idx), idx))SAT-verifier steps are about half of , always bounded by formula literal count. No exploration occurs: the certificate is read once. Now the solver and oracle.
def simplifica(cnf, lit):
"""Pone el literal lit a verdadero. Si aparece una cláusula vacía, el resultado la contiene."""
nuevo = []
for c in cnf:
if lit in c:
continue
nuevo.append([l for l in c if l != -lit] if -lit in c else c)
return nuevo
def dpll(cnf):
"""Decide SAT con propagación unitaria y ramificación (DPLL). cnf: lista de listas de enteros."""
while True:
if any(len(c) == 0 for c in cnf):
return False
unit = next((c[0] for c in cnf if len(c) == 1), None)
if unit is None:
break
cnf = simplifica(cnf, unit)
if not cnf:
return True
lit = min(cnf, key=len)[0]
return dpll(simplifica(cnf, lit)) or dpll(simplifica(cnf, -lit))
class Oraculo:
"""Caja negra de decisión que cuenta sus llamadas."""
def __init__(self, decide):
self.decide, self.llamadas = decide, 0
def __call__(self, *args):
self.llamadas += 1
return self.decide(*args)
def busca_asignacion(cnf, n, es_sat):
"""Encuentra una asignación usando solo es_sat(cnf) -> bool: n + 1 llamadas si hay solución."""
if not es_sat(cnf):
return None
asignacion = {}
for v in range(1, n + 1):
con_v = simplifica(cnf, v)
if es_sat(con_v): # x_v = 1 sigue siendo satisfacible
cnf, asignacion[v] = con_v, True
else: # entonces x_v = 0 lo es, sin preguntar
cnf, asignacion[v] = simplifica(cnf, -v), False
return asignacion
rng = random.Random(5)
for n in (10, 20, 30):
cnf, _ = sat_plantado(n, 3 * n, rng)
orac = Oraculo(dpll)
a = busca_asignacion(cnf, n, orac)
print(f"n = {n}: llamadas = {orac.llamadas} (n + 1 = {n + 1}), la asignación satisface la fórmula: {verifica_sat(cnf, a)[0]}")
orac = Oraculo(dpll)
print("insatisfacible (x1)(¬x1):", busca_asignacion([[1], [-1]], 1, orac), " llamadas:", orac.llamadas)The returned assignment is the first found by trying 1 before 0 for each variable and need not match the planted one. The important part is the count: exactly calls, even if the solver internally explores many more branches.
Now Cook–Levin. The machine is the figure’s. Rows, columns and cell alphabet are defined above; F implements the local rule; and to avoid trusting F, acepta_directo independently simulates the machine.
import time
from itertools import combinations, product
TAPE = "01_"
HALT = "YN"
DELTA = {("A", "0"): ("A", "0", "R"), ("A", "1"): ("B", "1", "R"), ("A", "_"): ("Y", "_", "R"),
("B", "0"): ("A", "0", "R"), ("B", "1"): ("N", "1", "R"), ("B", "_"): ("Y", "_", "R")}
SIMBOLOS = list(TAPE) + [q + a for q in "ABYN" for a in TAPE] # 15 símbolos: cinta o cabezal (estado + símbolo)
COLS, FILAS = 7, 6
cabezal = lambda s: len(s) == 2
def F(izq, c, der):
"""Nuevo contenido de una celda a partir de las tres de encima."""
if cabezal(c):
return c if c[0] in HALT else DELTA[(c[0], c[1])][1]
if cabezal(izq) and izq[0] not in HALT and DELTA[(izq[0], izq[1])][2] == "R":
return DELTA[(izq[0], izq[1])][0] + c
if cabezal(der) and der[0] not in HALT and DELTA[(der[0], der[1])][2] == "L":
return DELTA[(der[0], der[1])][0] + c
return c
def acepta_directo(bits):
"""Simulador de la máquina, independiente de F."""
cinta, q, pos = ["_"] + [str(b) for b in bits] + ["_"] * 3, "A", 1
while q not in HALT:
q, escribe, mov = DELTA[(q, cinta[pos])]
cinta[pos] = escribe
pos += 1 if mov == "R" else -1
return q == "Y"
def var(i, j, s):
return 1 + (i * COLS + j) * len(SIMBOLOS) + SIMBOLOS.index(s)
NV = FILAS * COLS * len(SIMBOLOS)
def construye_cnf(solo_admisibles):
cl = []
for i in range(FILAS): # cada celda tiene exactamente un símbolo
for j in range(COLS):
vs = [var(i, j, s) for s in SIMBOLOS]
cl.append(vs)
cl += [[-a, -b] for a, b in combinations(vs, 2)]
cl += [[var(0, 0, "_")], [var(0, 1, "A0"), var(0, 1, "A1")], # inicio: cabezal en A sobre w1
[var(0, 2, "0"), var(0, 2, "1")], [var(0, 3, "0"), var(0, 3, "1")]] # w2 y w3 libres
cl += [[var(0, j, "_")] for j in (4, 5, 6)]
cl.append([var(FILAS - 1, j, "Y" + a) for j in range(COLS) for a in TAPE]) # alguna celda con el cabezal en Y
for i in range(1, FILAS): # movimiento: una cláusula por celda y terna de encima
for j in range(COLS):
for l, c, r in product(SIMBOLOS if j > 0 else [None], SIMBOLOS, SIMBOLOS if j < COLS - 1 else [None]):
if solo_admisibles and sum(cabezal(x) for x in (l, c, r) if x) > 1:
continue
lits = [-var(i - 1, j + dj, x) for dj, x in ((-1, l), (0, c), (1, r)) if x]
cl.append(lits + [var(i, j, F(l or "_", c, r or "_"))])
return cl
def resuelve(cnf, nv=NV):
"""DPLL con propagación unitaria por listas de ocurrencias. Devuelve val[1..nv] (1 = verdadero) o None."""
idx = lambda l: 2 * l if l > 0 else -2 * l + 1
ocurre = [[] for _ in range(2 * nv + 2)]
for k, c in enumerate(cnf):
for l in c:
ocurre[idx(l)].append(k)
val, traza, pila = [0] * (nv + 1), [], []
def pon(l):
v = 1 if l > 0 else -1
if val[abs(l)] == v:
return True
if val[abs(l)] == -v:
return False
val[abs(l)] = v
traza.append(abs(l))
pila.append(l)
return True
def propaga():
while pila:
l = pila.pop()
for k in ocurre[idx(-l)]: # cláusulas que han perdido un literal
libres, ultimo, sat = 0, 0, False
for m in cnf[k]:
vm = val[abs(m)] * (1 if m > 0 else -1)
if vm == 1:
sat = True
break
if vm == 0:
libres, ultimo = libres + 1, m
if sat:
continue
if libres == 0 or (libres == 1 and not pon(ultimo)):
pila.clear()
return False
return True
def busca():
v = next((x for x in range(1, nv + 1) if val[x] == 0), None)
if v is None:
return True
for lit in (v, -v):
marca = len(traza)
if pon(lit) and propaga() and busca():
return True
pila.clear()
while len(traza) > marca:
val[traza.pop()] = 0
return False
for c in cnf:
if len(c) == 1 and not pon(c[0]):
return None
return val if propaga() and busca() else None
completa, admisible = construye_cnf(False), construye_cnf(True)
print(f"variables: {NV}, cláusulas: {len(completa)} (todas las ternas) o {len(admisible)} (solo ternas con a lo sumo un cabezal)")
def certificado(val):
return "".join(next(s for s in "01" if val[var(0, j, s)] == 1 or val[var(0, j, "A" + s)] == 1) for j in (1, 2, 3))
t0, cnf, modelos = time.time(), list(admisible), []
while True: # todos los modelos, bloqueando el certificado hallado
val = resuelve(cnf)
if val is None:
break
bits = certificado(val)
modelos.append(bits)
cnf.append([-var(0, 1, "A" + bits[0]), -var(0, 2, bits[1]), -var(0, 3, bits[2])])
aceptados = sorted("".join(map(str, b)) for b in product((0, 1), repeat=3) if acepta_directo(b))
print("certificados que dan una fórmula satisfacible:", sorted(modelos))
print("certificados que acepta la máquina (simulador): ", aceptados, " coinciden:", sorted(modelos) == aceptados)
for bits in ("101", "011"): # fijar el certificado y mirar la tabla
unidades = [[var(0, 1, "A" + bits[0])], [var(0, 2, bits[1])], [var(0, 3, bits[2])]]
val = resuelve(admisible + unidades)
print(f"\ncertificado {bits}:", "fórmula insatisfacible (la máquina rechaza)" if val is None else "tabla leída del modelo")
if val is not None:
for i in range(FILAS):
print(" ", " ".join(f"{next(s for s in SIMBOLOS if val[var(i, j, s)] == 1):>2}" for j in range(COLS)))Formula models are exactly the accepted certificates: the reduction is correct both ways, as required. Notice the second experiment: with certificate 011 the formula is unsatisfiable, not because the tableau is missing anything but because no legal tableau ends in acceptance. Windows force computation and only the certificate was free.
The fourth cell implements optimization-to-decision reduction for maximum clique with a brute-force oracle as black box, checking against networkx’s maximum clique (Bron–Kerbosch).
from itertools import combinations
from math import ceil, log2
import networkx as nx
def hay_clique(vertices, aristas, k):
"""Oráculo de decisión (por fuerza bruta): ¿hay k vértices de `vertices` dos a dos adyacentes?"""
V = sorted(vertices)
E = {frozenset(e) for e in aristas if e[0] in vertices and e[1] in vertices}
return any(all(frozenset(p) in E for p in combinations(c, 2)) for c in combinations(V, k))
def omega_por_decision(vertices, aristas, oraculo):
"""Tamaño del clique máximo con búsqueda binaria sobre k: como mucho ceil(log2 n) preguntas."""
lo, hi = 1, len(vertices) # todo grafo no vacío tiene un clique de tamaño 1
while lo < hi:
mid = (lo + hi + 1) // 2
if oraculo(vertices, aristas, mid):
lo = mid
else:
hi = mid - 1
return lo
def omega_networkx(n, aristas):
"""Referencia independiente: clique máximo exacto de networkx (enumera los cliques maximales)."""
G = nx.Graph()
G.add_nodes_from(range(n))
G.add_edges_from(aristas)
return max(len(c) for c in nx.find_cliques(G))
rng = random.Random(3)
print(" n p omega (networkx) omega (búsqueda binaria) llamadas ceil(log2 n)")
for n, p in [(8, 0.5), (12, 0.4), (14, 0.6), (16, 0.5), (16, 0.8)]:
aristas = [(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < p]
orac = Oraculo(hay_clique)
w = omega_por_decision(set(range(n)), aristas, orac)
ref = omega_networkx(n, aristas)
assert w == ref
print(f"{n:3d} {p:4.1f} {ref:16d} {w:24d} {orac.llamadas:8d} {ceil(log2(n)):12d}")Binary search computes only the optimum value. Constructing the clique needs the self-reduction above: another calls, decision-oracle calls total.
A final experiment reinforces a warning: “NP-complete” describes worst case. Random 3-SAT formulas with clauses on variables are almost always satisfiable when is small and almost always unsatisfiable when large, with a sharp transition around (empirical, not proved for 3-SAT). Measure our DPLL’s search-node work versus ratio .
nodos = 0
def dpll_cuenta(cnf):
global nodos
nodos += 1
while True:
if any(len(c) == 0 for c in cnf):
return False
unit = next((c[0] for c in cnf if len(c) == 1), None)
if unit is None:
break
cnf = simplifica(cnf, unit)
if not cnf:
return True
lit = min(cnf, key=len)[0]
return dpll_cuenta(simplifica(cnf, lit)) or dpll_cuenta(simplifica(cnf, -lit))
def al_azar(n, m, rng):
return [[v * rng.choice((-1, 1)) for v in rng.sample(range(1, n + 1), 3)] for _ in range(m)]
rng, n, N = random.Random(7), 40, 20
print(f"n = {n} variables, {N} fórmulas por razón")
print(" m/n satisfacibles nodos medios")
for razon in (2, 3, 4, 4.26, 5, 6, 8, 10):
total, sat = 0, 0
for _ in range(N):
nodos = 0
sat += dpll_cuenta(al_azar(n, round(razon * n), rng))
total += nodos
print(f"{razon:4} {sat:5d} de {N} {total / N:8.1f}")Solver work is small at both extremes (almost everything is satisfiable and a solution is quickly found, or almost everything unsatisfiable with early conflicts) and largest near the transition: with only 40 variables, about four times as many nodes at as , with the gap growing rapidly in . This helps explain why modern clause-learning SAT solvers handle huge industrial instances: NP-completeness says hard instance families exist, not that all are hard.
The professional version
In production, use a SAT solver instead of writing one. CDCL solvers (conflict-driven clause learning, covered internally in classical AI) descend from GRASP (1996) and Chaff (2001), routinely solving industrial instances with hundreds of thousands or millions of variables and clauses, as annual SAT competitions show. Common libraries expose an interface much like our oracle:
from pysat.solvers import Glucose3 # pip install python-sat; no se ejecuta en el navegador
import networkx as nx
with Glucose3(bootstrap_with=[[1, 2, -3], [-1, 3], [-2, -3]]) as s:
print(s.solve()) # decisión: True
print(s.get_model()) # búsqueda: una asignación, como [1, -2, -3]
print(s.solve(assumptions=[1, 3])) # el oráculo con variables fijadas, sin recopiar la fórmula
G = nx.gnp_random_graph(30, 0.5, seed=1)
omega = max(len(c) for c in nx.find_cliques(G)) # clique máximo exacto (Bron-Kerbosch), exponencial en el peor caso
Two details: solve(assumptions=...) is exactly self-reducibility’s “fix and ask” without rebuilding the formula, and is how model enumeration and SAT optimization are implemented. And constrained integer combinatorial optimization commonly uses CP-SAT or integer programming solvers, internally doing what our binary search does: improve a bound and ask whether a better solution exists.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What algorithm decides when ?
Step 1 of 5. How do we prove that each row is the configuration after steps?
busca_clique(vertices, aristas, k, oraculo). oraculo(vertices, aristas, k) is a black box that answers whether the graph formed by those vertices (and the edges between them) has a clique of size at least k. Your function returns a list of exactly k vertices forming a clique, or None if none exists, and can call the oracle at most `n + 1` times (n is the number of vertices). Use only the oracle to decide; the tests count calls. Hint: the approach is the self-reducibility you just saw for SAT.def busca_clique(vertices, aristas, k, oraculo):
"""Devuelve k vertices que formen un clique, o None, usando solo el oraculo de decision."""
# tu codigo
return NoneSummary
- A decision problem is language ; optimization reduces to decision by threshold binary search and search reduces to decision by testing variables one by one with calls. Input size is its bit count.
- is polynomial-time decidability, robust across computation models. consists of problems with short polynomially checkable certificates, or equivalently decided by nondeterministic machines in polynomial time. , and one inclusion is strict but which is unknown.
- means a polynomial function maps instances to instances with the same answer: is at least as hard as . Easiness goes against the arrow and hardness along it. To prove hard, reduce a hard problem to .
- NP-complete means NP-hard and in . An NP-complete problem in implies . Cook–Levin gives the first: any verifier’s -step execution is encoded in a tableau of cells, with cell, start, movement ( windows, one 4-literal clause per upper triple) and acceptance clauses.
- is the class of complements of . An NP-complete problem in collapses and . Factoring and linear programming (before 1979) lay in , suggesting they were not NP-complete.
- NP-hard does not mean impractical: SAT solvers handle enormous instances, and difficult random instances cluster in a narrow clause-to-variable-ratio region.