The art of reductions: a catalogue of NP-complete problems
Proving NP-completeness is a design skill: choose a source problem and build gadgets. Follow Karp's reduction tree from 3-SAT to independent set, clique and vertex cover, 3-coloring, Hamiltonian cycle and traveling salesperson, subset sum and partition. Distinguish weak from strong NP-hardness and extract reduction design patterns for new problems.
After this lesson you can
- Construct and prove reductions from 3-SAT to independent set, 3-coloring, Hamiltonian cycle and subset sum.
- Design choice and checking gadgets for new reductions.
- Distinguish strong and weak NP-hardness and relate them to pseudopolynomial algorithms.
- Choose the most suitable source problem to prove a new problem NP-complete.
- Automatically check reductions with a solver on small instances.
Before you start
Motivation: is an exact algorithm worth seeking?
Your platform team has integration test suites and a CI cluster. Two suites conflict if they need the same test database or port: they cannot run together. Two nearly identical questions arise. What is the largest number of suites that can run simultaneously? How many rounds are needed to distribute them so that no two suites in a round conflict? A colleague has spent a week trying to write an efficient exact algorithm. Before spending another week it is useful to know whether one exists.
The questions are, respectively, maximum independent set and minimum coloring on the conflict graph. The previous lesson established the theoretical tool: the Cook–Levin theorem gives a first NP-complete problem, SAT, and a polynomial reduction propagates hardness to any problem SAT reduces to. This lesson is about how to do that in practice. Proving a new problem NP-complete is a design skill, much like writing a small compiler: choose a suitable source problem, design local pieces (gadgets) that translate its elements into the target language, and prove that the translation preserves the answer in both directions.
The result saves money. If you prove your problem NP-complete, you stop looking for a polynomial exact algorithm (which would prove ) and turn to the realistic tools in lessons 30 and 31: branch and bound, parameterized algorithms, approximation and SAT solvers. The catalogue we build here (independent set, clique, cover, coloring, Hamiltonian cycle, traveling salesperson, subset sum, partition) is also the repertoire of source problems you will choose from.
The recipe for an NP-completeness proof
Recall the scheme. A problem is NP-complete if it belongs to NP and every problem in NP reduces to it in polynomial time. Since reduction is transitive, for a new problem it suffices to reduce one known problem.
The proof composes reductions: if via , then via , and the composition of two polynomial functions is polynomial. For design, what matters is how the work divides up. Every proof has five obligations, and beginners’ errors almost always occur in the third and fifth.
- Membership in NP. There is a polynomial-size certificate and a polynomial verifier (almost always trivial, but it must be stated).
- Choice of source. A known NP-complete problem with structure similar to .
- Construction. A function from instances of to instances of , computable in polynomial time. This includes having polynomial size in under the agreed input encoding.
- Forward direction. If is positive, is positive: construct a target solution from a source solution.
- Reverse direction. If is positive, is positive: recover a source solution from a target solution.
All reductions in this lesson also translate certificates in both directions using functions you will implement in the lab: from an assignment to an independent set and back. This is the level of rigor worth demanding, and it also allows automatic checking.
From SAT to 3-SAT
The reduction from SAT to 3-SAT is the first step. SAT permits clauses of any length; 3-SAT requires at most three literals per clause (or exactly three, depending on the version). A single problem with uniform structure is much more convenient as a source: the gadgets in the following sections are designed for fixed-size clauses.
The idea is to split each long clause with new variables linking its pieces. For a clause with , introduce and replace it by
Each says “the true literal appears later.” Short clauses are padded: becomes the four clauses with new , and becomes .
Proof
The size is linear: a clause of literals produces clauses and one of 1 or 2 literals produces 4 or 2. It suffices to prove each clause with satisfies the equivalence separately, using distinct new variables in each clause; the short clauses are immediate.
Forward. Given an assignment making some true, set for and for . Clause (), , is true by if , by if and by if . The edge cases (first and last clause, or ) are equally straightforward.
Reverse. If all were false, the first clause forces , the second , and so on until , and the last clause is false. Thus an assignment satisfying makes an original literal of true, and restricted to variables of satisfies .
∎Notice what is preserved: satisfiability, not models. and are not logically equivalent (they have different variables and different numbers of solutions): they are equisatisfiable. Polynomial reductions ask for exactly that.
Why 2-SAT is easy and where the trick breaks
Why stop at three? With two literals per clause, the problem stops being hard. A clause is equivalent to the two implications and . The implication graph has a vertex per literal and these arcs, and the 2-CNF formula is unsatisfiable if and only if some variable and its negation are in the same strongly connected component (from one reaches and vice versa: contradiction). With lesson 18 this is a linear algorithm.
The clause-splitting trick cannot go below three: cannot be written as a conjunction of two-literal clauses, even with auxiliary variables. The reason is elegant: if three assignments satisfy a 2-CNF, their coordinate-wise majority also satisfies it (in each clause , each of the three makes or true, so one is true in at least two), and that property survives ignoring auxiliary variables. But , and satisfy while their majority, , does not. There is a deeper reason, resolution: from two 2-literal clauses and one derives , again with 2 literals; the resolution closure has at most clauses and can be computed in polynomial time. With 3-literal clauses, and produce of size 4, and the closure can grow exponentially. The boundary between P and NP-complete is exactly between 2 and 3.
Independent set, clique and vertex cover
From 3-SAT to the first graph problem. A set of vertices is independent if no two of them are joined by an edge. The independent set problem asks, given a graph and integer , whether an independent set of size at least exists. Its two siblings are clique (a set of pairwise adjacent vertices) and vertex cover (a set touching every edge); the family is completed by complementation, as we will see.
The construction has two gadgets, one for each thing the formula must enforce. Given a 3-CNF formula with clauses, graph has:
- Choice gadget. For each clause , a triangle with three vertices, one per literal. Since they are adjacent, an independent set takes at most one per triangle: the literal that “serves” the clause.
- Consistency gadget. An edge between each literal and each literal from different clauses. Thus and are never selected together.
The target is : one vertex per clause.
Proof
Forward. Let be an assignment satisfying . In each clause choose a true literal and take its vertex. There are vertices, one per triangle, so there are no triangle edges between them. A conflict edge would join a chosen literal to a chosen , and both would be true under , which is impossible.
Reverse. Let be an independent set with . Each triangle contains at most one vertex of and there are triangles, so there is exactly one per clause. Define the assignment by making every chosen literal true (it is consistent: if and were both in , there would be an edge between them) and assigning any value to variables with no vertex in . Every clause has a true literal, so is satisfied.
∎The size of is polynomial: vertices and at most edges. And because a set of vertices is its own certificate. Thus independent set is NP-complete.
Clique and vertex cover by complementation
Two almost free reductions complete the family.
Proof
(1)(2): has no edges of if and only if all pairs in are edges of . (1)(3): is not independent if and only if there is an edge with , that is, an edge with neither endpoint in ; so is independent if and only if every edge has an endpoint in .
∎Thus reduces independent set to clique, and reduces it to vertex cover. Both are in NP and are NP-complete; the second, with its complete proof, is an exercise. The only cost of the first is constructing the complement, which can have edges: still polynomial.
3-coloring: palette, variables and the OR gate
Coloring is the prototype problem where the reduction constructs logic with colors. 3-coloring asks whether a graph can be colored with three colors so that no adjacent vertices share a color. The NP-completeness of 3-coloring is proved from 3-SAT using three gadgets.
Palette. A triangle with vertices , and (true, false and “base”). Since they are adjacent, every 3-coloring gives them three distinct colors; without loss of generality call these , and .
Variable. For each , two vertices and joined to each other and both joined to . Neither can have color and they cannot match: one is and the other . Choosing which is is choosing the value of the variable.
OR gate. With inputs and output : three new vertices with edges , , , and . Triangle uses all three colors.
Proof
(1) Since and , both are or , and since they are adjacent they differ: . The triangle forces .
(2) If : set (allowed because ), (allowed because , with ) and . If and : , and .
∎Clause. For chain two gates: , also joined to (so it is or ), and , with joined to and , forcing it to be . There are six vertices and thirteen edges per clause.
Proof
If all are : by (1), ; then the second gate has both inputs and by (1) , but is joined to . Impossible.
If one is : if or is, by (2) choose ; if , by (1) and . In both cases (compatible with its edge to ) and one input of the second gate is , so by (2) we can choose , compatible with its edges to and .
∎Proof
Forward. Given an assignment satisfying , color the palette , each true literal and each false literal (consistent with the variable), and complete each clause using the previous theorem, applicable because each clause has a true literal.
Reverse. In a proper 3-coloring, rename the colors so the palette is . Each literal is joined to , so is or , and , have opposite colors: they define the assignment “ is true if and only if its vertex is ”. Since each clause gadget is colored, the previous theorem guarantees some input is , i.e. a true literal.
∎The sizes are checked in the lab: for variables and clauses the graph has vertices and edges. And since 3-coloring is in NP (the coloring is the certificate), it is NP-complete. The arbitrary chromatic number and other colorings are NP-hard a fortiori (restriction pattern, below). For the opening example: scheduling suites in three conflict-free rounds is already NP-complete.
Hamiltonian cycles and the traveling salesperson
A Hamiltonian cycle visits each vertex exactly once. The Hamiltonian cycle and its traveling salesperson variant need a more sophisticated gadget: one cannot color or choose vertices, but must force a traversal. We first work with directed graphs.
The construction from 3-SAT to directed Hamiltonian cycle, for with variables and clauses :
- Variable ladder. For each , a row of vertices with arcs in both directions between consecutive vertices. Traversing it left to right means ; right to left, .
- Links. Arcs from a vertex to both ends of row 1; from each end of row to each end of row (four arcs); from both ends of row to a vertex ; and an arc .
- Clause vertices. A vertex per clause. If , arcs ; if , arcs . (As usual, assume no clause contains both and : it would be trivially true and can be removed.) Vertices , with , are separators: one before the first pair, one between every two consecutive pairs and one after the last, none at a row endpoint.
The asymmetry is the key: the detour through from left to right exists only for positive literals, and in the opposite direction only for negative ones. A row traversed to the right can visit clauses where appears positively, precisely those made true by .
Proof
Forward. With an assignment satisfying : the cycle starts at , traverses row left to right if and right to left otherwise, passes to the next row at an endpoint and ends at with arc . For each clause choose a true literal of variable ; when row passes positions , detour through : it exists because the row direction makes true. Every vertex is visited once.
Reverse. Let be a Hamiltonian cycle. Step 1: the detour returns to its row. Suppose enters from (positive literal) and exits to a vertex . Then cannot have predecessor (that vertex goes to ) or , so its predecessor is and its successor, which cannot be (that would form a two-vertex cycle), is . But then , the previous separator, whose only neighbors are and , has only as possible predecessor (because already has a successor) and only as possible successor (because already has a predecessor): would contain the two-vertex cycle . Contradiction. The negative case is symmetric, with the next separator playing the role of ; it also works for because is not the row endpoint ( is), which is why every row has a separator beyond its last pair.
Step 2: each row is traversed in one direction. Replacing each detour with the direct arc between its two row vertices, each interior row vertex has only its two row neighbors. If the predecessor of is , its successor is and so on to the end, and conversely. Thus the entire row is traversed from one end to the other and rows are visited in order.
Step 3. Define if row is traversed left to right. Each is visited from some row by a detour existing only when the row direction makes the literal of in true. Hence satisfies every clause.
∎From directed to undirected. Replace each vertex by three, , joined in that order by two edges, and each arc by edge . A directed cycle gives a cycle traversing each triplet from to . Conversely, has only two neighbors, so every Hamiltonian cycle goes through , and on leaving can only enter an : all triplets are traversed in the same direction and this is a directed cycle. This is a local replacement: each vertex is replaced by a fixed piece. Undirected Hamiltonian cycle is NP-complete.
Traveling salesperson. The decision problem receives distances between cities and a bound , and asks whether a tour visits them all with total length at most . Given a graph with vertices, define if and otherwise, with . A Hamiltonian cycle is a tour of length exactly ; a tour of length has segments of length 1, so uses only graph edges. One line of proof suffices because traveling salesperson contains Hamiltonian cycle as a special case. Note: the distances are 1 and 2, small numbers, a fact that matters in the strong hardness section.
Subset sum and partition
So far all numbers were small. The subset sum problem receives integers and a target and asks whether some subset sums to exactly ; partition asks whether the integers can be split into two groups with equal sum. The reduction from 3-SAT is a beautiful encoding: digits act as independent columns, and the trick is to ensure there are no carries.
Given with variables and clauses (with distinct variables within each clause), all numbers have decimal digits: the first for variables and the last for clauses.
- For each variable , two numbers (true) and (false). Both have a 1 in the digit for ; also has a 1 in the digit of each clause containing , and in that of each clause containing . The rest are zeros.
- For each clause , two equal slack numbers, with a single 1 in its digit.
- The target has a 1 in each of the first digits and a 3 in each of the last .
For example, with (the first interactive formula) there are 7-digit numbers. Separating variable and clause columns, (variable and clauses and , where it appears positively), (with in and ), the two slack numbers for are , and the target is .
Proof
No carries. Each column sums to at most 5: a variable column receives at most its two numbers, and a clause column at most three literal numbers (one per clause literal) plus the two slack numbers. Since , adding integers is equivalent to column-by-column addition, and the target is reached if and only if every column reaches its required sum.
Forward. With an assignment satisfying , take if is true and otherwise: each variable column sums to 1. The column of receives as many ones as the clause has true literals, a number ; add slack numbers and it sums to 3.
Reverse. If a subset sums to , the column of forces choosing exactly one of : this defines an assignment. The column of sums to 3 with at most 2 from slack, so at least one literal number contributes a 1: a true literal.
∎The conceptual key is size: the numbers have digits, so their value reaches , exponential in the formula size. The produced instance has digits in total, so the value of is as a function of that length : superpolynomial, which is what matters. As we will see, this is why the reduction proves only weak NP-hardness.
From subset sum to partition. Given with and , add the two numbers and . The total sum is , and we seek two groups of sum . Since , and cannot be in the same group (if ); in the group containing the rest sums to . Thus a partition exists if and only if some subset of sums to . If or , the answer is no and the instance maps to a fixed negative instance. You will program this reduction.
Knapsack. Knapsack (is there a subset of weight at most and value at least ?) contains subset sum with value equal to weight and : another restriction. Knapsack is weakly NP-complete and pseudopolynomial dynamic programming solves it in .
Weak and strong NP-hardness
The subset sum reduction creates numbers with digits. Subset sum dynamic programming costs . Does this contradict NP-completeness? No: is exponential in , and is superpolynomial in input length. It is a pseudopolynomial algorithm: polynomial in values, not in the number of bits. Two types of hardness must be distinguished.
Proof
Let be the polynomial in the definition. On instances with , the algorithm time, polynomial in and , is polynomial in . That restriction is NP-hard and is in P: .
∎Consequence: subset sum, partition and knapsack are not strongly NP-hard unless , since they have pseudopolynomial dynamic programming. Strongly NP-hard problems resist even with small numbers. Three examples:
- Traveling salesperson already is: the reduction from Hamiltonian cycle uses distances 1 and 2.
- 3-partition: given integers with and sum , can they be divided into triples each summing to ? Garey and Johnson proved it strongly NP-complete (the reduction, via three-dimensional matching, keeps numbers polynomially bounded; we cite it without proof).
- Bin packing: do items of sizes fit in bins of capacity ? From 3-partition: bins must be full (the total sum is ) and since , each bin has exactly three items. So a 3-partition is a packing and vice versa. With polynomial numbers: strong. Scheduling on identical machines (minimizing completion time) is proved similarly.
The boundary has a practical interpretation. If your problem only has moderate numbers (times in seconds, weights up to ) and is weakly hard, DP may solve it in practice; if strongly hard, no scaling trick saves it.
Karp’s map
Karp (1972) brought together 21 problems in a reduction tree rooted at SAT. Each edge is a reduction like those in this lesson. The interactive below contains those 21 and four more we used (independent set, 3-coloring, traveling salesperson and 3-partition), with the paths followed here (which sometimes differ from Karp’s: each edge says so). Click a problem to see its reduction gadget, solution translation, instance size and a worked example; try adding your own problem.
Two observations about the map. First is economy: a short chain from SAT reaches almost everything, and each new edge only requires designing one gadget. Second is size: composing reductions whose size grows like gives a final instance of size , polynomial as long as is constant. This does not matter in a fixed-depth tree, but it is useful to choose sources close to the target (shorter, less blowup, simpler gadgets).
Reduction design patterns
Looking at the previous reductions reveals a repertoire. We call these reduction design patterns.
Restriction. The target contains the source as a special case, and the reduction is (almost) the identity. 3-coloring chromatic number (); subset sum knapsack (value equals weight); Hamiltonian cycle traveling salesperson (distances 1 and 2); vertex cover set cover (each element in two sets). It is the shortest proof and the first to try: is a special case of my problem a known problem?
Local replacement. Replace each element of the source instance with a fixed target piece. A long clause by a chain of three-literal clauses; a directed vertex by an undirected triplet; an undirected edge by a directed cycle of length 2 (from vertex cover to feedback vertex set in Karp’s map). Correctness is proved piece by piece.
Component design. When neither suffices, design gadgets with separate functions:
| Reduction | Choice | Check | Consistency | Threshold |
|---|---|---|---|---|
| 3-SAT independent set | one vertex per clause (triangle) | the chosen literal serves the clause | edges between opposite literals | |
| 3-SAT 3-coloring | or colored | OR gate with output joined to F and B | triangle | three colors |
| 3-SAT Hamiltonian cycle | row direction | clause vertex with detour | each row traversed in one direction | cycle visits everything |
| 3-SAT subset sum | or | clause digit with slack | variable digit | target |
The scheme is always the same: choose a value per variable, check each clause, force the choice to be consistent, and set a threshold (a , a color, a target) attained only if all checks pass. The hard part is almost never checking but consistency: this is where the gadget must stop the choice from “cheating” (a detour that does not return to its row, a literal chosen both ways, a carry between digits).
Choosing the source. The best source usually has the same “shape” as your problem:
| Your problem concerns… | Natural source |
|---|---|
| choosing a subset with pairwise restrictions (conflicts) | independent set, clique |
| covering something with few elements | vertex cover or set cover |
| assigning labels or colors with incompatibilities | 3-coloring, 3-SAT |
| a traversal visiting everything once | Hamiltonian cycle |
| splitting numbers into equal groups (large values) | partition, subset sum |
| splitting numbers into equal groups (small values) | 3-partition |
| logic with general constraints | 3-SAT |
Checklist for a complete proof. Before accepting a proof, make these six checks: (a) , with certificate and verifier; (b) source is NP-complete and not a disguised easy case (reducing 2-SAT or a special case of in P does not work); (c) is defined for every instance of , including degenerate cases (clauses with repeated literals, , edgeless graphs); (d) is polynomial in time and output size; (e) forward direction proved, with translated certificate; (f) reverse direction proved, with translated certificate. If you can run and a solver on small instances on both sides, do it: the analogue of a unit test (you will do this in the lab).
Practical problems that turn out to be NP-hard
The catalogue is not a museum. Some problems you will work with are NP-hard, explaining entire tools:
- Optimal decision trees. Hyafil and Rivest (1976) proved building the optimal binary decision tree (one minimizing, for example, the expected number of questions) NP-complete. This is why ID3, CART and their descendants grow trees greedily: there is no shortcut to the global optimum (module 11).
- K-means. It is NP-hard even in the plane (Mahajan, Nimbhorkar and Varadarajan, 2009), and also with in arbitrary dimension (Dasgupta, 2008; Aloise et al., 2009). Lloyd’s algorithm guarantees only a local optimum, and smart initializations (-means++) are an approximation measure, not exactness (module 12).
- Package dependency resolution. Deciding whether an installation consistent with a package manager’s version constraints exists is NP-complete (Mancinelli et al., 2006); Russ Cox clearly explained it as “Version SAT” (2016). Modern managers incorporate SAT solvers or CDCL-like algorithms precisely for this reason (module 0).
These are not the only examples: Blum and Rivest (1992) proved that training a three-node neural network to fit data is NP-complete. In all these cases NP-hardness is a worst-case statement and does not prevent real instances from being tractable: see lesson 33.
Implementation from scratch
The best check of a reduction is to run it. The next cell implements the three main reductions (3-SAT to independent set, 3-coloring and subset sum) as functions generating instances, solves both sides by brute force or branching on small random formulas (plus a hand-made unsatisfiable one), and checks that answers agree and certificates translate in both directions. This is exactly what the checklist asks.
import itertools, random, time
def rand_formula(n, m, rng):
"""m cláusulas de 3 literales (pueden repetirse variables); literal +i es x_i y -i es ¬x_i."""
return [tuple(rng.choice((1, -1)) * rng.randint(1, n) for _ in range(3)) for _ in range(m)]
def sat_brute(n, clauses):
for bits in itertools.product((False, True), repeat=n):
if all(any(bits[abs(l) - 1] == (l > 0) for l in c) for c in clauses):
return bits
return None
# ---------- 3-SAT -> conjunto independiente ----------
def red_indep(clauses):
m = len(clauses)
lit = [l for c in clauses for l in c] # vértice v = 3j + p
edges = {(3 * j + p, 3 * j + q) for j in range(m) for p, q in ((0, 1), (0, 2), (1, 2))}
edges |= {(u, v) for u in range(3 * m) for v in range(u + 1, 3 * m)
if u // 3 != v // 3 and lit[u] == -lit[v]}
return 3 * m, edges, m, lit
def max_indep(nv, edges):
"""Conjunto independiente máximo por ramificación: o se toma el vértice de mayor grado o se descarta."""
adj = {v: set() for v in range(nv)}
for u, v in edges:
adj[u].add(v); adj[v].add(u)
best = []
def rec(cand, chosen):
nonlocal best
if len(chosen) + len(cand) <= len(best):
return
if not cand:
best = list(chosen); return
v = max(cand, key=lambda x: len(adj[x] & cand))
rec(cand - adj[v] - {v}, chosen + [v]) # tomar v
rec(cand - {v}, chosen) # descartar v
rec(set(range(nv)), [])
return best
def assignment_from_indep(lit, S, n):
a = [False] * n
for v in S:
a[abs(lit[v]) - 1] = lit[v] > 0
return tuple(a)
def indep_from_assignment(clauses, a):
return [3 * j + next(p for p, l in enumerate(c) if a[abs(l) - 1] == (l > 0)) for j, c in enumerate(clauses)]
# ---------- 3-SAT -> 3-coloración ----------
def red_color(n, clauses):
"""Vértices 0, 1, 2 = T, F, B; literal x_i = 3 + 2(i-1), ¬x_i = 4 + 2(i-1); luego 6 vértices por cláusula."""
lit = lambda l: 3 + 2 * (abs(l) - 1) + (l < 0)
E = [(0, 1), (0, 2), (1, 2)]
for i in range(1, n + 1):
E += [(lit(i), lit(-i)), (lit(i), 2), (lit(-i), 2)]
nv = 3 + 2 * n
for c in clauses:
a, b, d = (lit(l) for l in c)
x1, y1, o1, x2, y2, o2 = range(nv, nv + 6); nv += 6
E += [(a, x1), (b, y1), (x1, y1), (x1, o1), (y1, o1), (o1, 2), # OR(a, b) -> o1, con o1 != B
(o1, x2), (d, y2), (x2, y2), (x2, o2), (y2, o2), (o2, 1), (o2, 2)] # OR(o1, c) -> o2 = T
return nv, E, lit
def colorear(nv, E, pre):
"""Backtracking con el vértice más restringido primero; `pre` fija colores de partida."""
adj = [set() for _ in range(nv)]
for u, v in E:
adj[u].add(v); adj[v].add(u)
col = {0: 0, 1: 1, 2: 2, **pre}
def libres(v):
return [c for c in range(3) if all(col.get(u) != c for u in adj[v])]
def rec():
pend = [v for v in range(nv) if v not in col]
if not pend:
return True
v = min(pend, key=lambda x: len(libres(x)))
for c in libres(v):
col[v] = c
if rec():
return True
del col[v]
return False
return dict(col) if rec() else None
# ---------- 3-SAT -> suma de subconjuntos ----------
def red_ssum(n, clauses):
m, D = len(clauses), n + len(clauses)
num = lambda digs: int("".join(map(str, digs)))
nums, tag = [], []
for i in range(1, n + 1):
for sgn in (1, -1):
d = [0] * D; d[i - 1] = 1
for j, c in enumerate(clauses):
d[n + j] = int(sgn * i in c)
nums.append(num(d)); tag.append(("lit", sgn * i))
for j in range(m):
d = [0] * D; d[n + j] = 1
nums += [num(d)] * 2; tag += [("slack", j)] * 2
return nums, int("1" * n + "3" * m), tag
def subset_sum(nums, T):
"""Meet-in-the-middle: devuelve los índices de un subconjunto de suma T o None."""
h = len(nums) // 2
def sums(idx):
out = {0: ()}
for i in idx:
for s, sub in list(out.items()):
out.setdefault(s + nums[i], sub + (i,))
return out
A, B = sums(range(h)), sums(range(h, len(nums)))
for s, sub in A.items():
if T - s in B:
return sub + B[T - s]
return None
def ssum_from_assignment(n, clauses, tag, a):
chosen = [k for k, t in enumerate(tag) if t[0] == "lit" and (t[1] > 0) == a[abs(t[1]) - 1]]
for j, c in enumerate(clauses):
verdaderos = sum(a[abs(l) - 1] == (l > 0) for l in set(c))
chosen += [k for k, t in enumerate(tag) if t == ("slack", j)][: 3 - verdaderos]
return chosen
# ---------- comprobación: fórmulas al azar y las tres reducciones ----------
rng = random.Random(28)
inst = [(3, [(1, 2, 2), (1, -2, -2), (-1, 2, 2), (-1, -2, -2)])] # una insatisfacible a mano
inst += [(3, rand_formula(3, rng.randint(8, 12), rng)) for _ in range(15)]
cuenta = {"sat": 0, "insat": 0}
t0 = time.perf_counter()
for n, cl in inst:
a = sat_brute(n, cl)
nv, Ei, k, lit = red_indep(cl)
S = max_indep(nv, Ei)
nv2, Ec, litv = red_color(n, cl)
pre = {litv(i if a[i - 1] else -i): 0 for i in range(1, n + 1)} if a else {}
col = colorear(nv2, Ec, pre)
nums, T, tag = red_ssum(n, cl)
sub = subset_sum(nums, T)
positiva = a is not None
assert (len(S) >= k) == (col is not None) == (sub is not None) == positiva, (cl, positiva)
if not positiva:
cuenta["insat"] += 1
continue
cuenta["sat"] += 1
# certificados en las dos direcciones
S1 = indep_from_assignment(cl, a)
assert len(S1) == k and not any(u in S1 and v in S1 for u, v in Ei) # asignación -> independiente
a2 = assignment_from_indep(lit, S[:k], n)
assert all(any(a2[abs(l) - 1] == (l > 0) for l in c) for c in cl) # independiente -> asignación
a3 = tuple(col[litv(i)] == 0 for i in range(1, n + 1)) # coloración -> asignación
assert all(any(a3[abs(l) - 1] == (l > 0) for l in c) for c in cl)
ch = ssum_from_assignment(n, cl, tag, a) # asignación -> subconjunto
assert sum(nums[i] for i in ch) == T
a4 = tuple(any(tag[i] == ("lit", v) for i in sub) for v in range(1, n + 1)) # subconjunto -> asignación
assert all(any(a4[abs(l) - 1] == (l > 0) for l in c) for c in cl)
print("fórmulas:", len(inst), cuenta, " | último caso:", nv, "vértices (IS),", nv2, "vértices (3-COL),", len(nums), "números de", len(str(T)), "dígitos")
print("todas las reducciones coinciden con la fuerza bruta y los certificados se traducen en los dos sentidos")Notice three things. First, the triple assertion: the four answers (the formula and the three targets) must agree on every instance, including unsatisfiable ones, where half a reduction fails. Second, certificates: ssum_from_assignment is the forward direction of the proof (choose one number per variable and complete with slack) and reading sub is the reverse. Third, size: in the last output case (, ), 3-coloring produces a graph with vertices, and subset sum 28 numbers with 14 digits: a target of order , for which DP is already impractical.
The boundary between weak and strong, in an experiment
The second lab makes the difference visible. We solve subset sum two ways: pseudopolynomial DP, using a Python integer as a bitset (bit indicates sum is reachable), and meet-in-the-middle (lesson 30), which generates all sums of each half and matches them, at cost independent of number size. We measure each cost by counting cells and sums, independent of the clock.
import random, time
def dp_subset_sum(nums, T):
"""DP pseudopolinómica: un entero de Python hace de bitset (el bit s indica «la suma s es alcanzable»)."""
reach, mask = 1, (1 << (T + 1)) - 1
for a in nums:
reach |= (reach << a) & mask
return (reach >> T) & 1 == 1
def mitm_subset_sum(nums, T):
"""Meet-in-the-middle: todas las sumas de cada mitad y una búsqueda cruzada. Coste ~ 2^(n/2), sin depender de T."""
h = len(nums) // 2
def sums(a):
out = [0]
for x in a:
out += [s + x for s in out]
return out
left, right = sums(nums[:h]), set(sums(nums[h:]))
return any(T - s in right for s in left)
def instancia(n, bits, rng):
"""n enteros de a lo sumo `bits` bits y un objetivo alcanzable (suma de la mitad de ellos)."""
nums = [rng.randrange(1, 1 << bits) for _ in range(n)]
return nums, sum(nums[::2])
rng = random.Random(7)
n = 20
print(f"n = {n}: celdas de la DP (n·T) frente a sumas de MITM (2·2^(n/2) = {2 * 2 ** (n // 2)})")
print(f"{'bits':>5} {'celdas DP':>14} misma respuesta")
for bits in (4, 8, 12, 16, 20):
nums, T = instancia(n, bits, rng)
r1, r2 = dp_subset_sum(nums, T), mitm_subset_sum(nums, T)
print(f"{bits:>5} {n * (T + 1):>14,} {r1 == r2 == True}")
# Números grandes: la DP ni cabe en memoria (haría falta un bitset de ~2^64 bits); MITM no se entera
nums, T = instancia(n, 64, rng)
print(f"\nn = {n}, 64 bits: la DP necesitaría ~{n * T:.2e} celdas; MITM responde {mitm_subset_sum(nums, T)}")
# Números pequeños: n = 60 con 10 bits. MITM necesitaría 2^31 sumas; la DP, 60·T celdas
nums, T = instancia(60, 10, rng)
print(f"n = 60, 10 bits: DP responde {dp_subset_sum(nums, T)} con {60 * (T + 1):,} celdas; MITM haría {2 ** 31:,} sumas")
# Densidad: qué fracción del rango [0, Σ] de objetivos es alcanzable (n = 16)
print("\ndensidad de sumas alcanzables, n = 16")
for bits in (4, 8, 12, 16, 20):
nums = [rng.randrange(1, 1 << bits) for _ in range(16)]
reach, S = 1, sum(nums)
for a in nums:
reach |= reach << a
print(f" {bits:>2} bits: {reach.bit_count() / (S + 1):6.1%} de los {S + 1:,} objetivos")The table tells the whole story. For 4-bit numbers DP needs about 1380 cells, fewer than the 2048 MITM sums; for 8 bits it is already , and for 20 bits, . DP cost grows with the value of the numbers; MITM cost only with . In the second part the regions separate completely: with 64 bits DP is impossible and MITM still takes milliseconds, while with and 10 bits the reverse holds, sums versus fewer than a million cells. Neither is polynomial in input size, but each exploits a kind of structure. Density completes the picture: with 4 bits all targets are reachable (the instance is “dense” and almost always positive), while with 20 bits only a small fraction are; real subset sum hardness lies in the intermediate region.
The library version
You need not write every solver. An integer linear program with binaries checks the independent-set reduction in one line of modeling, and the relationship with vertex cover comes for free: if is the size of the smallest cover, . We add the first lab’s unsatisfiable formula to also see the case.
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
def ilp_indep(nv, edges):
"""max sum x_v sujeto a x_u + x_v <= 1 en cada arista, x binaria."""
A = np.zeros((len(edges), nv))
for r, (u, v) in enumerate(sorted(edges)):
A[r, u] = A[r, v] = 1
res = milp(c=-np.ones(nv), constraints=LinearConstraint(A, ub=1), integrality=np.ones(nv), bounds=Bounds(0, 1))
return int(round(-res.fun))
def ilp_cover(nv, edges):
"""min sum x_v sujeto a x_u + x_v >= 1 en cada arista, x binaria."""
A = np.zeros((len(edges), nv))
for r, (u, v) in enumerate(sorted(edges)):
A[r, u] = A[r, v] = 1
res = milp(c=np.ones(nv), constraints=LinearConstraint(A, lb=1), integrality=np.ones(nv), bounds=Bounds(0, 1))
return int(round(res.fun))
rng2 = random.Random(5)
for n, cl in [inst[0]] + [(3, rand_formula(3, rng2.randint(8, 12), rng2)) for _ in range(4)]:
nv, Ei, k, lit = red_indep(cl)
a_ilp, tau = ilp_indep(nv, Ei), ilp_cover(nv, Ei)
a_bb = len(max_indep(nv, Ei))
print(f"m = {len(cl):2d}: α(ILP) = {a_ilp}, α(ramificación) = {a_bb}, τ(ILP) = {tau}, α + τ = {a_ilp + tau} = 3m = {nv}; satisfacible: {sat_brute(n, cl) is not None}, α = m: {a_ilp == k}")In a real solver, the model is the reduction: the gadgets you just wrote translate a problem into a format (SAT, ILP, SMT) an industrial solver can tackle. This is the highest-value use of all this material: when an NP-complete problem appears in production, reduce it to SAT or ILP and let years of solver engineering do the work (lesson 30).
Typical mistakes
Exercises
Step 1 of 4. Forward: given an assignment satisfying , what set do you construct?
Step 1 of 4. With , what color is and why?
Step 1 of 4. Membership in NP: what certificate and verifier do you use?
ssum_a_particion(a, T), which receives a list of positive integers a and a target T and returns an integer list for the equivalent partition instance: the list has a partition (two equal-sum groups) if and only if some subset of a sums to T. If T < 0 or T > sum(a), return [1] (a fixed negative instance). Do not modify a.def ssum_a_particion(a, T):
"""Devuelve una lista de enteros con partición si y solo si algún subconjunto de a suma T."""
S = sum(a)
# tu código: casos fuera de rango, y los dos números que se añaden
return list(a)Summary
- Five obligations per proof: membership in NP, NP-complete source, polynomial construction, forward and reverse. Reducing backwards or proving only one direction is the classic error.
- 3-SAT is the universal source: fixed-size clauses. 2-SAT is in P (implication graph and strongly connected components); the boundary is between 2 and 3 literals.
- Independent set: a triangle per clause and edges between opposite literals, with ; counts satisfiable clauses. Clique and vertex cover follow by complementation.
- 3-coloring: palette, variable and OR gate with output forced to T. Hamiltonian cycle: one ladder per variable whose direction is its value, and a clause vertex with a detour; traveling salesperson is a special case with distances 1 and 2.
- Subset sum: decimal digits without carries and slack numbers; partition with numbers and . The -digit numbers explain weak hardness (pseudopolynomial DP); 3-partition, traveling salesperson and bin packing are strong.
- Patterns: restriction, local replacement and components. The difficult part is always consistency. Optimal decision trees, -means and dependency resolution are NP-hard: hence greedy algorithms, Lloyd and solvers.