Coping with NP-hardness: exact, parameterized and fine-grained algorithms
NP-hardness does not end the conversation. Study exact algorithms improving on brute force, including branch and bound and meet-in-the-middle; parameterized complexity through bounded search trees, kernelization and FPT; ETH and SETH; and fine-grained complexity, which explains why polynomial-time problems such as edit distance and all-pairs shortest paths resist substantial improvement.
After this lesson you can
- Implement branch and bound with relaxation bounds and measure the effect of the quality of the bound.
- Solve the subset sum with meet-in-the-middle and analyze its cost.
- Design FPT algorithms and kernels for vertex cover and related problems.
- Use ETH and SETH to obtain conditional lower bounds.
- Explain the fine-grained reduction connecting edit distance to SETH.
Before you start
Motivation: NP-hard is not the end of the conversation
The lesson on NP-completeness ends with a verdict: if your problem is NP-hard, do not expect a polynomial-time algorithm. Yet NP-hard problems are solved exactly every day. Hardware verification issues millions of SAT queries with hundreds of thousands of variables. Airlines assign crews through integer programs with millions of variables. In 2006, Concorde proved optimality of a traveling-salesperson tour through cities, instance pla85900 from an actual circuit-manufacturing problem. None contradicts theory: theory concerns the worst case over all inputs of size , whereas the inputs that matter have structure.
This lesson explains how to exploit that structure and, when it is absent, prove that substantially better algorithms are unlikely. There are four distinct questions:
- How much better than brute force? Enumerating subsets or permutations is the starting point. Branch and bound discards entire regions using bounds; meet-in-the-middle replaces by ; and a careful branching analysis improves maximum independent set from to .
- Where is the explosion? If exponential dependence is confined to a small parameter , such as solution size or graph treewidth, an algorithm taking can be practical despite NP-hardness. This is parameterized complexity. One of its most useful tools is kernelization: polynomial-time preprocessing reducing any instance to a core whose size is bounded by .
- Can we do better still? Answering ‘probably not’ requires a stronger assumption than P NP: the Exponential Time Hypothesis, ETH, and its strong version, SETH, yield precise conditional lower bounds.
- What about polynomial-time problems? Edit distance has had a quadratic algorithm since 1974, and all-pairs shortest paths a cubic algorithm since Floyd-Warshall. Fine-grained complexity uses the same hypotheses to explain why those exponents resist improvement. The reduction establishing this for edit distance is fundamentally another meet-in-the-middle construction.
Branching and pruning
Backtracking with bounds
Consider 0/1 knapsack: items with positive integer weights and values , and capacity . Seek subject to and . Exhaustive search traverses a depth- binary tree: level decides whether to take item , and each leaf represents one of assignments. Backtracking already prunes something: once accumulated weight exceeds , no extension is feasible and the branch is abandoned. This is insufficient, however, because almost every small subset fits into a half-full knapsack.
The decisive question at each node is how much value could possibly be gained by completing its partial decision. If this cannot exceed the best known solution, discard the entire subtree.
Correctness is immediate: a pruned node contains no solution better than , since all its solutions have value at most . Efficiency is not immediate; it depends entirely on bound tightness. The trivial bound prunes nothing. With the exact bound , exploring the child with the largest bound first leads directly to an optimum, and every other node is pruned when visited. Computing that bound, however, is as hard as the original problem. Practical engineering lies between these extremes.
At a knapsack node where some items have already been decided, with accumulated value and weight , there are two natural bounds:
- Trivial bound: , as though every remaining item could fit.
- Fractional bound: the optimum of the subproblem’s linear relaxation, allowing each undecided item to be taken fractionally, .
The linear relaxation has a closed-form solution, which makes knapsack the textbook example.
Proof
Let be an optimal LP solution. If and some , increasing strictly improves value. Thus an optimum either takes everything or fills capacity. Suppose with and . Move weight from to : for small , set and . Total weight stays unchanged, while value changes by . Repeating this exchange without worsening the solution yields one where no denser item is incomplete while a less-dense item is taken at all: exactly the stated greedy solution. Hence the greedy solution is also optimal.
∎This is an exchange argument of the kind used in greedy algorithms. It gives a bound computable in per node, or using prefix sums and binary search. Its validity is a general property of relaxations: the integer feasible set lies inside the continuous one, so the continuous maximum is at least as large. This is the same convex-relaxation idea used in optimization, here serving exact search.
Integer values let us tighten the test: every integer solution’s value is integral, so prune whenever .
What you should have observed:
- The fractional bound with density ordering proves optimality in 53 nodes. The optimum is 176 and the root bound is already : the LP relaxation differs by only units. Almost any branch departing from the greedy solution drops the bound below 177, whose integer part no longer exceeds 176, and is pruned within one or two levels.
- The trivial bound needs nodes; no value bound needs . The root’s trivial bound is the sum of all values, 310, so pruning begins only after enough items have been excluded. Without a value bound, only over-capacity nodes are discarded, and all feasible leaves are reached. A useful bound can save two orders of magnitude; a poor one may save none.
- Ordering matters, but only with a good bound. With the fractional bound, deciding dense items first reduces the node count from 237 to 53: the first explored branch nearly matches the greedy solution, giving a strong incumbent immediately. With the trivial bound, the same ordering makes matters worse, from to , because that bound ignores capacity and cannot exploit a strong incumbent.
- Best-first search visits even fewer nodes: 41 with density ordering and 33 with input ordering, where ordering scarcely matters anymore, because it always expands the largest-bound node. The price is retaining the entire open frontier in memory. Depth-first search uses memory, so industrial solvers combine both strategies.
What real solvers do
A mixed-integer programming solver such as CPLEX, Gurobi, HiGHS or SCIP uses branch and bound with the full integer problem’s LP relaxation as its bound. Dual simplex reuses the parent’s basis. Three additions matter: cutting planes, inequalities valid for integer solutions that remove fractional vertices and improve the bound, giving branch and cut; primal heuristics, finding strong incumbents early; and presolve, reduction rules simplifying the instance before search. Modern SAT solvers descended from DPLL also backtrack, but use unit propagation and clause learning rather than a numerical bound. Each conflict produces a clause pruning future branches that would repeat the same mistake. Game-search alpha-beta pruning is branch and bound with two incumbents, one per player.
Meet-in-the-middle
Subset sum asks whether some subset of sums exactly to . It is NP-complete but admits pseudopolynomial time through dynamic programming over capacity. With large numbers, such as 60-bit integers, is astronomical and enumeration remains. Enumerating subsets costs . There is a much better approach.
Proof
Split the numbers into and the remainder . Every subset uniquely decomposes as , with and , and its sum is . Generate lists and containing the and sums of the two halves, then sort . For each , binary-search for in . A subset summing to exists exactly when a search succeeds. Doubling generates the lists in time; sorting costs , as do the searches. Memory consists of the two lists.
∎Two refinements help. The lists are already sorted if generated by merging: sums for are the merge of the sums for and those same sums shifted by , two sorted lists. Total generation cost is . Two pointers traversing upward and downward then make the whole algorithm . A hash table on removes sorting altogether, trading worst-case cost for expected cost.
Memory does not improve: sums are stored. At , each list contains eight-byte integers, taking 8 GiB. Schroeppel and Shamir (1981) reduced memory to without increasing time by splitting into four quarters and generating each half’s sums in order using two heaps, without storing them all. Whether subset sum admits has been open since 1974.
The general pattern: when a solution splits into two parts interacting only through a simple condition, such as a sum, intermediate state or ciphertext, enumerate both halves and join them using a data structure. Cost changes from to plus the join. This will reappear unexpectedly at the end: the SAT reduction underlying fine-grained complexity is itself meet-in-the-middle.
Exact exponential algorithms
When no small parameter is available, the question is the exponential base. To suppress polynomial factors, write , meaning . Since for every , the base is what matters. You already know one example: Held-Karp solves traveling salesperson in rather than . Another example, maximum independent set, illustrates the field’s central technique.
Branching with a measure
Brute force for independent set tests subsets. A branching algorithm proceeds as follows:
- If a vertex has degree 0 or 1, take it and delete and its neighbor. This is safe: if an optimum contains the neighbor , replacing with gives another optimum because has no other neighbors.
- If every vertex has degree 2, the graph is a disjoint union of cycles. A cycle of length contributes .
- Otherwise, some vertex has degree at least 3. Branch: either is excluded, deleting and leaving vertices, or it is included, deleting and its neighbors and leaving at most .
Let count worst-case search-tree leaves. Step 3 gives ; steps 1 and 2 do not branch.
Proof
The function is continuous and strictly decreasing on , tending to at and to at . Since , there is exactly one root of . Choose such that for . Inductively, if the bound holds for every , then .
∎For the equation is , with root . Polynomial work per node makes the three-rule algorithm : at , compare with . The vector is the branching vector. Improving such an algorithm means finding rules guaranteeing better vectors: choosing a vertex of degree at least 4, for example, gives vector and .
The decisive refinement changed what is measured. Instead of counting vertices, Fomin, Grandoni and Kratsch (2009) weight each vertex by degree: a degree-2 vertex costs less than a degree-5 vertex because it is easier to eliminate. They analyze the recurrence in this measure. This measure-and-conquer method barely changes the algorithm but proves with polynomial memory. Xiao and Nagamochi (2017) reduced this to . In the same spirit, Schöning’s random walk (1999) solves 3-SAT in , and PPSZ variants fall below .
Parameterized complexity
The preceding exponential algorithms depend on , the size of the whole input. Often a much smaller quantity captures the actual difficulty: desired solution size, graph treewidth, or the number of variables appearing in many constraints. Parameterized complexity, developed by Downey and Fellows in the 1990s, studies algorithms whose exponential dependence is confined to that quantity.
The difference between FPT and XP can determine whether an instance is solvable in practice. With and , operations correspond to about a quarter of an hour, whereas would never finish. The canonical example is vertex cover: does some with touch every edge?
The idea fits in one line: choose any uncovered edge . Every cover contains or , so branch on these alternatives, each with budget . The tree has depth and at most leaves. A guided exercise gives the complete proof. The key point is that the parameter bounds the tree’s depth, rather than graph size.
Richer branching gives smaller bases. If vertex has degree at least 3, either belongs to the cover or all its neighbors do; otherwise the edge to an omitted neighbor is uncovered. This gives branching vector and base , the root of . If every degree is at most 2, solve the disjoint paths and cycles directly. Much finer case analysis led Chen, Kanj and Xia (2010) to .
The parameter is everything
A set is a vertex cover exactly when is independent: the same problem, but with the parameter changing from to . Yet independent set parameterized by solution size does not appear to be FPT. Downey and Fellows organized these problems in the W hierarchy, , with parameterized reductions preserving a bound on the parameter. Clique and independent set parameterized by are W[1]-complete; dominating set is W[2]-complete. All lie in XP by trying subsets. The conjecture plays the role that P NP plays in classical complexity. Below, ETH gives a quantitative version: clique cannot be solved in .
Kernelization
An even simpler FPT approach to vertex cover than the search tree explains why industrial solver preprocessing works so well.
Proof
Given a kernel, compute it in polynomial time, then solve the size- result with any algorithm: cost is polynomial plus a function of . Conversely, let run in time. If , takes at most time, which is polynomial: run it and return a constant-sized trivial instance with the same answer. If , the original instance already has size below and serves as its own kernel.
∎This proof is a bookkeeping trick: the kernel may have exponential size . The interesting question is which problems admit small kernels. Vertex cover has two classical examples.
Buss’s rules
Buss and Goldsmith (1993) identified three rules to apply repeatedly:
- High degree. If vertex has degree greater than , belongs to every cover of size ; otherwise all its more than neighbors would be needed. Include , delete it and set . If becomes negative, answer NO.
- Isolated vertices. An isolated vertex belongs to no minimum cover. Delete it.
- Too many edges. If neither preceding rule applies and more than edges remain, answer NO: each vertex covers at most edges, so vertices cover at most .
An exercise proves each rule’s correctness and the size bound. Without isolated vertices, every vertex is either in the cover or neighbors one of its vertices, each having at most neighbors. More than remaining vertices therefore also imply NO. Combining the kernel with branching solves vertex cover in : the exponential term no longer multiplies the original graph size.
Watch rule 1 cascade at . The first three hubs have degrees 12, 11 and 10, all greater than 9, so they enter the cover and reduce the budget to 6. The fourth hub, degree 7, did not exceed the original threshold but exceeds the new one and enters too. All 40 leaves become isolated and disappear under rule 2. A pentagon and triangle remain: 8 vertices and 8 edges with , far below . The pentagon requires 3 vertices and the triangle 2, exactly the budget. Search visits 13 nodes: its first branch takes , , and , spending four vertices on the pentagon and leaving too little for the triangle; backtracking finds . With , the kernel is identical but , and search visits all nodes before answering NO. With , no search is needed: 8 edges remain and .
A kernel of 2k vertices by linear programming
Buss’s kernel has vertices. The vertex-cover LP relaxation gives a linear-sized kernel:
Proof
(a) Let be a polyhedron vertex, and define and . Set and . For small , bounds remain satisfied. An edge with has slack. If , either both coordinates equal and remain unchanged, or they are 0 and 1 and remain unchanged, or one endpoint lies in and the other in , canceling their changes. Thus and are feasible and . Since is a vertex, , giving .
(b) We accept part (b), whose proof uses an exchange argument on a matching between and . For size, restricting to is feasible for the relaxation on and is optimal: a better solution combined with elsewhere would improve the original optimum and remain feasible. All neighbors of lie in , since an endpoint assigned 0 forces the other to 1, and edges between and are already covered. Hence lower-bounds the minimum cover of . If that cover fits within , then .
∎In the figure’s graph, the LP optimum assigns 1 to all four hubs, 0 to leaves, and to the kernel’s eight vertices. A pentagon needs 3 integral vertices but only fractionally; a triangle needs 2 versus . Here the LP and Buss kernels coincide. A kernel with vertices can have edges, essentially optimal in bit size: Dell and van Melkebeek (2010) proved that vertex cover has no kernel encodable in bits unless . Related techniques show that some FPT problems, such as a path of length , admit no polynomial kernel under that assumption.
Treewidth as a parameter
Solution size is not the only useful parameter. In structured dynamic programming you saw tree decompositions and treewidth: a width- graph decomposes into bags of at most vertices arranged as a tree. Each bag separates what lies below it from what lies above. Here treewidth becomes the parameter.
A nice decomposition has four node types: leaves with empty bags; nodes introducing vertex , whose bag is the child’s bag plus ; nodes forgetting it, whose bag is the child’s bag minus ; and join nodes with two children having identical bags. Every width- decomposition becomes a nice decomposition of the same width with nodes. For maximum independent set, let be induced by vertices appearing in the subtree of . For every independent , let be the size of the largest independent set in satisfying . The transitions are:
- Leaf: .
- Introduce : if and is independent; if .
- Forget : .
- Join: .
Correctness follows from the separator property: and interact only through the shared bag, whose vertices have been counted twice at a join. Each table has entries, giving cost : FPT in width and linear in . Bodlaender (1996) proved that, for fixed , a width- decomposition can be found in linear time with constant . Courcelle’s theorem generalizes this dynamic programming to properties expressible in monadic second-order logic. The same separator argument connects two other modules: tree decompositions of CSPs and variable elimination in graphical models have costs exponential in width.
Is the right base? Lokshtanov, Marx and Saurabh (2011) proved that, under the hypothesis introduced next, independent set cannot be solved in for any . The textbook dynamic program is therefore probably optimal even in its base.
ETH and SETH: conditional lower bounds
P NP excludes polynomial-time 3-SAT, but is compatible with or algorithms. Ruling these out requires a quantitative hypothesis. Define
This is a nondecreasing sequence with , because 2-SAT is linear, and by brute force.
SETH implies ETH, and both imply P NP. Neither is proved. Their support comes from decades of -SAT algorithms whose exponent improvements vanish as , and a coherent theory of consequences. ETH becomes useful through the sparsification lemma (Impagliazzo, Paturi and Zane, 2001), allowing clauses without losing the bound. It implies that ETH excludes -time 3-SAT.
Proof
(1) Classical reductions from 3-SAT, including SAT to 3-SAT and catalog reductions such as 3-coloring, produce graphs with vertices and edges from formulas with variables and clauses. A algorithm on the resulting graph, with , would solve 3-SAT in , contradicting sparsified ETH. (2) Since , a algorithm would be , contradicting (1). (3) This needs a finer reduction grouping variables into blocks, which we omit.
∎Notice what (2) says: the search tree cannot become subexponential in , so only the base can improve. Statement (1) also has a surprising positive interpretation. On planar graphs, many of these problems admit algorithms, because the planar separator theorem gives treewidth . Reductions from 3-SAT to planar graphs are quadratic-sized, so ETH excludes : the square root is exactly the right dependence.
SETH gives finer lower bounds with exact bases: CNF-SAT has no algorithm, by definition; independent set has no algorithm parameterized by treewidth ; and, most strikingly, it yields lower bounds for polynomial-time problems.
Fine-grained complexity
Edit distance has been computable in since Wagner and Fischer (1974), with only logarithmic-factor improvements in half a century. All-pairs shortest paths, APSP, take , and the best known improvement is smaller than every fixed power of . Finding three numbers summing to zero among inputs, 3SUM, takes by sorting and using two pointers, with similar stagnation. NP-completeness says nothing here: all are in P. The question is why their exponents are 2 or 3 rather than or .
The bridge from SAT to polynomial-time problems looks innocent.
Proof
Let be a CNF formula with variables , assuming even for simplicity, and clauses . Split the variables into and the remaining . For each of the assignments to , define by
and similarly define for every assignment to . Then exactly when every clause has a literal satisfied by or in : equivalently, the full assignment satisfies . Building the vectors costs . Taking and , the hypothetical algorithm takes . For -SAT with fixed , , so is polynomial in and -SAT would run in for every , contradicting SETH.
∎This is meet-in-the-middle: enumerate assignments to both halves separately, then combine through an orthogonal pair. Sparsification additionally lets us assume , hence , the OV-conjecture regime. From OV, hardness propagates to string and graph problems.
The reduction turns two vector lists into two strings of length . Each coordinate becomes a small string gadget whose alignment costs slightly less when at least one of the corresponding coordinates of and is 0. A vector concatenates its coordinate gadgets; final strings interleave vectors with padding forcing every inexpensive alignment to pair complete vectors across lists. Total edit distance falls below a computable threshold exactly when an orthogonal pair exists. A edit-distance algorithm would solve OV in and, by the preceding theorem, CNF-SAT in . Lesson 15’s quadratic dynamic program is therefore essentially optimal unless SETH fails. Similar results hold for longest common subsequence, Fréchet distance between curves and diameter approximation in sparse graphs.
Three observations about this network:
- There are families, rather than one hierarchy. No fine-grained reduction is known in either direction between SETH, 3SUM and APSP. Carmosino and colleagues (2016) proved that, under nondeterministic SETH, NSETH, 3SUM and APSP cannot be SETH-hard through deterministic fine-grained reductions. They are three independent conjectures; zero-weight triangle is interesting precisely because it inherits two of them.
- The APSP family contains equivalences. Vassilevska Williams and Williams (2010) proved that APSP, min-plus matrix multiplication, negative-weight triangle and several other problems are subcubically equivalent: either all have algorithms or none does. Detecting one negative triangle seems easier than computing distances, but is not.
- The chain back to SAT is short. A edit-distance algorithm would yield for OV and then for CNF-SAT, an improvement the SAT community has not achieved in decades.
Lab: exact algorithms from scratch
The following cells implement the lesson’s techniques in pure Python, using NumPy for large enumerations. Each browser cell runs in a few seconds. Instead of asking how large an instance can be solved in one minute, we measure work growth and extrapolate.
First, knapsack branch and bound with both bounds, compared against capacity-based dynamic programming. Sort by density, explore taking the item first, and prune using .
import random
def mochila_instancia(n, semilla, iguales=False):
rnd = random.Random(semilla)
if iguales: # v = w, pesos pares y capacidad impar
w = [2 * rnd.randint(10**4, 10**5) for _ in range(n)]
return w, w[:], (sum(w) // 2) | 1
w = [rnd.randint(10, 40) for _ in range(n)]
v = [wi + rnd.randint(-3, 10) for wi in w]
return w, v, sum(w) // 2
def mochila_dp(w, v, C):
f = [0] * (C + 1)
for wi, vi in zip(w, v):
for c in range(C, wi - 1, -1):
if f[c - wi] + vi > f[c]:
f[c] = f[c - wi] + vi
return f[C]
def mochila_bb(w, v, C, cota="fraccionaria"):
"""Ramificación y poda en profundidad. Devuelve (óptimo, nodos visitados)."""
n = len(w)
orden = sorted(range(n), key=lambda i: -v[i] / w[i]) # por densidad
w = [w[i] for i in orden]
v = [v[i] for i in orden]
suf = [0] * (n + 1)
for i in range(n - 1, -1, -1):
suf[i] = suf[i + 1] + v[i]
mejor, nodos = 0, 0
def cota_de(d, valor, cap):
if cota == "trivial":
return valor + suf[d]
b = valor # relajación lineal: voraz por densidad, el último partido
for i in range(d, n):
if w[i] <= cap:
b += v[i]
cap -= w[i]
else:
return b + v[i] * cap / w[i]
return b
def visitar(d, valor, cap):
nonlocal mejor, nodos
nodos += 1
if cap < 0 or int(cota_de(d, valor, cap)) <= mejor:
return
if d == n:
mejor = valor
return
visitar(d + 1, valor + v[d], cap - w[d]) # tomar primero
visitar(d + 1, valor, cap) # dejar
visitar(0, 0, C)
return mejor, nodos
print(" n óptimo nodos (trivial) nodos (fraccionaria) 2^(n+1) - 1")
for n in [10, 13, 16, 19, 30, 45, 60]:
w, v, C = mochila_instancia(n, n)
opt = mochila_dp(w, v, C)
triv = mochila_bb(w, v, C, "trivial")[1] if n <= 19 else "·"
valor, nodos = mochila_bb(w, v, C)
assert valor == opt
print(f"{n:2d} {opt:6d} {triv:>15} {nodos:>20} {2**(n + 1) - 1:>18}")
print("\nla misma cota fraccionaria con todas las densidades iguales:")
for n in [12, 14, 16, 18]:
w, v, C = mochila_instancia(n, n, iguales=True)
valor, nodos = mochila_bb(w, v, C)
print(f"n = {n}: óptimo {valor} (capacidad {C}), nodos {nodos:>7} de {2**(n + 1) - 1:>7} ({nodos / 2**(n + 1):.0%})")With distinct item densities, the fractional bound proves a 60-item optimum while visiting fewer than two hundred nodes of a -node tree; the trivial bound already needs almost a hundred thousand nodes for 19 items. Equal densities change the story. Whenever remaining items cannot all fit, the relaxation fills capacity and has value exactly . Since is odd and every sum is even, the incumbent never exceeds and this bound never prunes those nodes. Pruning begins only when remaining items cannot fill capacity. The visited tree occupies between a fifth and half of nodes, showing clean exponential growth: a measured version of the earlier warning.
Next, meet-in-the-middle. todas_las_sumas generates the sums of numbers by doubling with NumPy. Brute force generates them for all numbers; the faster version handles each half, joins through searchsorted and reconstructs indices from list positions. Bit of a position indicates whether number of that half was taken.
import random
import time
import numpy as np
def todas_las_sumas(a):
"""Las 2^len(a) sumas de subconjuntos; la posición i corresponde al subconjunto con los bits de i."""
s = np.zeros(1, dtype=np.int64)
for x in a:
s = np.concatenate([s, s + x])
return s
def suma_fuerza_bruta(a, T):
return bool(np.any(todas_las_sumas(a) == T))
def suma_mitm(a, T):
"""Índices de un subconjunto de a que suma T, o None."""
h = len(a) // 2
izq, der = todas_las_sumas(a[:h]), todas_las_sumas(a[h:])
orden = np.argsort(der, kind="stable")
der_ord = der[orden]
faltan = T - izq
pos = np.minimum(np.searchsorted(der_ord, faltan), len(der_ord) - 1)
hay = np.nonzero(der_ord[pos] == faltan)[0]
if len(hay) == 0:
return None
i = int(hay[0])
j = int(orden[pos[i]])
return [k for k in range(h) if i >> k & 1] + [h + k for k in range(len(a) - h) if j >> k & 1]
rnd = random.Random(0)
print(" n fuerza bruta 2^n (s) meet-in-the-middle (s) memoria de una mitad")
for n in [16, 18, 20, 22, 28, 34, 40]:
a = [rnd.randint(1, 10**12) for _ in range(n)]
T = sum(a[i] for i in rnd.sample(range(n), n // 3))
tb = "·"
if n <= 22:
t0 = time.perf_counter()
assert suma_fuerza_bruta(a, T)
tb = f"{time.perf_counter() - t0:.3f}"
t0 = time.perf_counter()
sol = suma_mitm(a, T)
tm = time.perf_counter() - t0
assert sol is not None and sum(a[i] for i in sol) == T
print(f"{n:2d} {tb:>20} {tm:>22.3f} {8 * 2**(n - n // 2) / 2**20:>14.3f} MiB")Each extra number theoretically doubles brute-force work but multiplies meet-in-the-middle work by . Measured times broadly follow this, with sorting and memory accesses also mattering for large lists. The faster method solves in a fraction of a second. Extrapolating brute force to gives hours, and this vectorized implementation would additionally need 8 TiB to store sums. Watch the final column: at each half takes 8 MiB; at , 8 GiB per half. Memory becomes limiting before time.
The three-rule independent-set algorithm, checked against brute force on a small graph and measured on random graphs of mean degree 4:
import random
def mis_ramificando(adj):
"""Tamaño del conjunto independiente máximo y nodos del árbol de búsqueda."""
nodos = 0
def rec(vivos):
nonlocal nodos
nodos += 1
if not vivos:
return 0
grado = {u: len(adj[u] & vivos) for u in vivos}
u = min(vivos, key=grado.get)
if grado[u] <= 1: # regla 1: tomar u es seguro
return 1 + rec(vivos - adj[u] - {u})
v = max(vivos, key=grado.get)
if grado[v] >= 3: # regla 3: ramificar (n - 1, n - 4)
return max(rec(vivos - {v}), 1 + rec(vivos - adj[v] - {v}))
total, vistos = 0, set() # regla 2: todo grado 2, unión de ciclos
for s in vivos:
if s in vistos:
continue
pila, comp = [s], {s}
while pila:
x = pila.pop()
for y in adj[x] & vivos:
if y not in comp:
comp.add(y)
pila.append(y)
vistos |= comp
total += len(comp) // 2
return total
return rec(frozenset(adj)), nodos
def grafo_aleatorio(n, grado_medio, semilla):
rnd = random.Random(semilla)
adj = {i: set() for i in range(n)}
aristas = 0
while aristas < n * grado_medio // 2:
u, v = rnd.randrange(n), rnd.randrange(n)
if u != v and v not in adj[u]:
adj[u].add(v)
adj[v].add(u)
aristas += 1
return {u: frozenset(s) for u, s in adj.items()}
def mis_fuerza_bruta(adj):
n, mejor = len(adj), 0
for S in range(1 << n):
if all(not (S >> v & 1) for u in range(n) if S >> u & 1 for v in adj[u]):
mejor = max(mejor, bin(S).count("1"))
return mejor
for semilla in range(3):
g = grafo_aleatorio(13, 3, semilla)
assert mis_ramificando(g)[0] == mis_fuerza_bruta(g)
print("coincide con la fuerza bruta en tres grafos de 13 vértices")
print("\n n α(G) nodos del árbol cota 1.3803^n")
for n in [20, 30, 40, 50, 60]:
a, nodos = mis_ramificando(grafo_aleatorio(n, 4, n))
print(f"{n:2d} {a:4d} {nodos:15d} {1.3803**n:13.3g}")Now parameterized vertex cover: Buss’s rules, search on the kernel and, for comparison, the LP kernel. Instances have known optimum by construction, combining hubs with many leaves, triangles, pentagons and isolated vertices. Measure search with , a YES instance, and , a NO instance requiring the expensive exhaustion of every branch.
import random
import time
import numpy as np
from scipy.optimize import linprog
def instancia_vc(hubs, triangulos, pentagonos, semilla):
rnd = random.Random(semilla)
aristas, n = [], 0
def nuevo():
nonlocal n
n += 1
return n - 1
for _ in range(hubs):
h = nuevo()
for _ in range(rnd.randint(30, 60)):
aristas.append((h, nuevo()))
for _ in range(triangulos):
a, b, c = nuevo(), nuevo(), nuevo()
aristas += [(a, b), (b, c), (c, a)]
for _ in range(pentagonos):
p = [nuevo() for _ in range(5)]
aristas += [(p[i], p[(i + 1) % 5]) for i in range(5)]
n += 50 # vértices aislados
rnd.shuffle(aristas)
return n, aristas, hubs + 2 * triangulos + 3 * pentagonos
def kernel_buss(aristas, k):
"""(forzados, aristas del núcleo, k restante), o None si la respuesta es NO."""
vivas, forzados = set(aristas), []
while True:
grado = {}
for u, v in vivas:
grado[u] = grado.get(u, 0) + 1
grado[v] = grado.get(v, 0) + 1
altos = [u for u, g in grado.items() if g > k]
if not altos:
break
u = max(altos, key=grado.get) # regla 1
forzados.append(u)
vivas = {e for e in vivas if u not in e}
k -= 1
if k < 0:
return None
if len(vivas) > k * k: # regla 3 (la 2 es implícita: solo hay aristas)
return None
return forzados, sorted(vivas), k
def vc_arbol(aristas, k):
"""Árbol de búsqueda acotado: (recubrimiento o None, nodos visitados)."""
nodos = 0
def rec(elegidos, k):
nonlocal nodos
nodos += 1
e = next(((u, v) for u, v in aristas if u not in elegidos and v not in elegidos), None)
if e is None:
return set(elegidos)
if k == 0:
return None
for x in e: # u o v está en todo recubrimiento
elegidos.add(x)
r = rec(elegidos, k - 1)
elegidos.discard(x)
if r is not None:
return r
return None
return rec(set(), k), nodos
def vc_fpt(aristas, k):
ker = kernel_buss(aristas, k)
if ker is None:
return None, 0, 0
forzados, nucleo, kk = ker
sol, nodos = vc_arbol(nucleo, kk)
return (None if sol is None else set(forzados) | sol), nodos, len(nucleo)
print(" k* n m aristas núcleo nodos (k = k*) nodos (k = k* - 1) tiempo (s)")
for hubs, tri, pen in [(4, 1, 1), (5, 2, 1), (6, 2, 2), (6, 3, 2), (8, 3, 3)]:
n, A, opt = instancia_vc(hubs, tri, pen, hubs)
t0 = time.perf_counter()
sol, nodos_si, mk = vc_fpt(A, opt)
assert sol is not None and len(sol) <= opt and all(u in sol or v in sol for u, v in A)
sol_no, nodos_no, _ = vc_fpt(A, opt - 1)
assert sol_no is None
print(f"{opt:3d} {n:5d} {len(A):5d} {mk:14d} {nodos_si:14d} {nodos_no:18d} {time.perf_counter() - t0:10.3f}")
# núcleo de Nemhauser-Trotter: un vértice óptimo de la relajación lineal (símplex dual)
n, A, opt = instancia_vc(6, 3, 2, 6)
M = np.zeros((len(A), n))
for i, (u, v) in enumerate(A):
M[i, u] = M[i, v] = -1
r = linprog(np.ones(n), A_ub=M, b_ub=-np.ones(len(A)), bounds=(0, 1), method="highs-ds")
x = r.x
print(f"\nrelajación lineal: valor {r.fun:.1f} frente al óptimo entero {opt}")
print("¿semientera?", bool(np.allclose(2 * x, np.round(2 * x))))
V1, Vm, V0 = int(np.isclose(x, 1).sum()), int(np.isclose(x, 0.5).sum()), int(np.isclose(x, 0).sum())
print(f"V1 = {V1} (concentradores), V1/2 = {Vm} (núcleo), V0 = {V0}")
print(f"núcleo lineal: {Vm} vértices <= 2(k* - |V1|) = {2 * (opt - V1)}")In all five instances, Buss’s kernel contains exactly the triangle and pentagon edges: rule 1 selects hubs and their leaves disappear. Search with finds a solution with little backtracking, between 7 and 159 nodes. With , it visits nodes, where : the theorem’s exact worst case, because every branch spends budget without covering everything. The final row has nodes with ; each extra budget unit would double the tree regardless of original graph size. As predicted, the LP kernel is half-integral: 6 hubs receive 1, leaves 0, and the 19 triangle and pentagon vertices . This is below because each triangle needs 2 integral vertices but only fractionally, and each pentagon 3 versus .
The final cell checks Williams’s reduction: random 3-CNF formulas with 12 variables, near the satisfiability threshold, become two lists of vectors. Matrix multiplication detects orthogonal pairs.
import random
import numpy as np
def cnf_aleatoria(n, m, k, rnd):
"""Literales como enteros con signo: +i es x_i, -i es su negación (i desde 1)."""
return [[(v + 1) * rnd.choice([1, -1]) for v in rnd.sample(range(n), k)] for _ in range(m)]
def satisfacible(n, F):
return any(all(any((x >> (abs(l) - 1) & 1) == (l > 0) for l in c) for c in F) for x in range(1 << n))
def vectores(F, variables):
"""Una fila por asignación de 'variables'; columna j a 0 si esa asignación satisface la cláusula j."""
V = np.ones((1 << len(variables), len(F)), dtype=np.int64)
for x in range(1 << len(variables)):
valor = {var: (x >> i) & 1 for i, var in enumerate(variables)}
for j, c in enumerate(F):
if any(abs(l) - 1 in valor and valor[abs(l) - 1] == (l > 0) for l in c):
V[x, j] = 0
return V
rnd = random.Random(3)
n, coinciden, sat = 12, 0, 0
for prueba in range(30):
F = cnf_aleatoria(n, rnd.choice([40, 50, 55, 60]), 3, rnd)
A = vectores(F, list(range(n // 2)))
B = vectores(F, list(range(n // 2, n)))
hay_ortogonal = bool(np.any(A @ B.T == 0))
coinciden += hay_ortogonal == satisfacible(n, F)
sat += hay_ortogonal
print(f"{coinciden}/30 fórmulas: par ortogonal <=> satisfacible ({sat} satisfacibles)")
print(f"tamaño de la instancia OV: N = 2^{n // 2} = {2 ** (n // 2)} vectores por lista, d = m cláusulas")The professional version: an industrial solver
An integer-programming solver applies our knapsack branch-and-bound idea with stronger bounds, cuts and heuristics. SciPy includes one: scipy.optimize.milp calls HiGHS, an industrial-quality open-source solver. The cell compares a large random knapsack, easy for every method; the hard equal-density family and meet-in-the-middle on that family; and vertex cover on the lab instance.
import random
import time
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds
def mochila_milp(w, v, C, exacto=True):
w, v = np.asarray(w, float), np.asarray(v, float)
opciones = {"mip_rel_gap": 0} if exacto else {} # 0: exige demostrar el óptimo
r = milp(-v, constraints=LinearConstraint(w[None, :], -np.inf, C), integrality=np.ones(len(w)),
bounds=Bounds(0, 1), options=opciones)
return round(-r.fun), r.mip_node_count
# 1) mochila aleatoria con 1000 objetos: la relajación es casi exacta
rnd = random.Random(1)
w = [rnd.randint(10, 40) for _ in range(1000)]
v = [wi + rnd.randint(-3, 10) for wi in w]
t0 = time.perf_counter()
print("1000 objetos:", mochila_milp(w, v, sum(w) // 2), f"{time.perf_counter() - t0:.2f} s (óptimo, nodos)")
# 2) densidades iguales: la cota lineal no informa y los nodos se disparan
for n in [12, 14, 16]:
rnd = random.Random(n)
w = [2 * rnd.randint(10**4, 10**5) for _ in range(n)]
C = (sum(w) // 2) | 1
t0 = time.perf_counter()
val, nodos = mochila_milp(w, w, C)
t1 = time.perf_counter() - t0
# el mismo problema por meet-in-the-middle: la mejor suma <= C cruzando dos listas ordenadas
h = n // 2
L = np.array([sum(w[i] for i in range(h) if S >> i & 1) for S in range(1 << h)])
R = np.sort([sum(w[h + i] for i in range(n - h) if S >> i & 1) for S in range(1 << (n - h))])
t0 = time.perf_counter()
j = np.searchsorted(R, C - L, side="right") - 1
mejor = int(np.max(np.where(j >= 0, L + R[np.maximum(j, 0)], -1)))
t2 = time.perf_counter() - t0
print(f"iguales, n = {n}: HiGHS {val} en {t1:.2f} s y {nodos} nodos; meet-in-the-middle {mejor} en {t2:.4f} s")
val_def, nodos_def = mochila_milp(w, w, C, exacto=False)
print(f" con el hueco por defecto: {val_def} en {nodos_def} nodos ({'óptimo' if val_def == val else f'le faltan {val - val_def}'})")
# 3) vertex cover como programa entero, sobre una instancia del laboratorio
n, A, opt = instancia_vc(8, 3, 3, 8)
M = np.zeros((len(A), n))
for i, (u, v2) in enumerate(A):
M[i, u] = M[i, v2] = 1
t0 = time.perf_counter()
r = milp(np.ones(n), constraints=LinearConstraint(M, 1, np.inf), integrality=np.ones(n), bounds=Bounds(0, 1))
print(f"vertex cover: HiGHS {round(r.fun)} (óptimo {opt}) en {time.perf_counter() - t0:.2f} s y {r.mip_node_count} nodos")Three readings matter. On the large random knapsack, HiGHS proves optimality at the root without branching: the LP value has integer part equal to optimum , so the bound certifies any primal-heuristic solution of that value. On equal densities, the industrial solver suffers like our fractional bound, visiting thousands of nodes for 16 items, whereas the structure-specific meet-in-the-middle algorithm joins its lists in under a millisecond. For vertex cover, the LP value is 20, assigning to triangle and pentagon vertices, versus integral optimum 23. HiGHS presolve and cuts close that gap at the root. Finally, inspect the default-gap rows. Without mip_rel_gap = 0, HiGHS stops once the relative incumbent-bound gap falls below . This is not an optimality proof: at it reports successful termination after 232 nodes with , six units below optimum. Equal-density instances have tiny relative gaps almost immediately, exactly where default tolerance can mislead.
Outside the browser, OR-Tools CP-SAT is a de facto standard for combinatorial problems. It combines constraint propagation, CDCL-style clause learning, linear relaxations and parallel search. Vertex cover can be written as follows; this example does not run here because OR-Tools is unavailable in the browser:
from ortools.sat.python import cp_model
def vertex_cover_cpsat(n, aristas, segundos=10):
m = cp_model.CpModel()
x = [m.NewBoolVar(f"x{v}") for v in range(n)]
for u, v in aristas:
m.AddBoolOr([x[u], x[v]]) # cada arista tiene un extremo elegido
m.Minimize(sum(x))
s = cp_model.CpSolver()
s.parameters.max_time_in_seconds = segundos
s.parameters.num_workers = 8 # búsqueda en cartera, en paralelo
estado = s.Solve(m)
return s.StatusName(estado), int(s.ObjectiveValue()), s.BestObjectiveBound()
StatusName distinguishes OPTIMAL, proved optimality, from FEASIBLE, a solution found without closing the bound gap. BestObjectiveBound reports the proven search bound, the same incumbent-bound pair used by branch and bound.
Typical errors
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. Why is it correct to branch only with and with ?
Step 1 of 4. Why does rule 1 preserve the answer?
suma_subconjunto(a, T): given a list a of up to 40 positive integers (of up to ) and a target T, return a list of distinct indices whose elements sum exactly to T, or None if it does not exist. It should take less than 3 seconds with in the browser, so enumeration of subsets is ruled out: use meet-in-the-middle. You can use NumPy (for example, np.concatenate, np.argsort and np.searchsorted). The empty subset sums 0.import numpy as np
def suma_subconjunto(a, T):
"""Índices de un subconjunto de a con suma T, o None."""
# 1) parte a en dos mitades y genera las 2^(n/2) sumas de cada una
# 2) ordena las de la derecha y busca T - s para cada suma s de la izquierda
# 3) reconstruye los índices a partir de las posiciones (bits) de las dos sumas
return NoneSummary
- Branch and bound: prune every node whose optimistic bound cannot improve the incumbent. The knapsack LP is density-greedy with one fractional item. Replacing the trivial bound with the fractional bound saves orders of magnitude; equal densities defeat it and restore exponential search.
- Meet-in-the-middle: subset sum falls from to by enumerating and joining two halves, using memory. The same idea breaks double encryption.
- Exact algorithms: branching recurrences yield bases such as for independent set. Measure and conquer improves the analysis by changing the measure.
- FPT and kernels: vertex cover admits search and kernels with edges by Buss’s rules or vertices through half-integral LP. FPT is equivalent to kernelizability. Independent set is W[1]-hard by solution size but FPT by treewidth, using dynamic programming.
- ETH and SETH: conditional lower bounds exclude for classical NP-complete problems, for vertex cover and for clique, with exact-base bounds under SETH.
- Fine-grained complexity: SETH implies the OV conjecture through meet-in-the-middle on assignments; OV reduces to edit distance, LCS and diameter problems, whose quadratic algorithms are optimal unless SETH fails. 3SUM and APSP organize two further families, with no known reductions between them.