Dynamic programming over intervals, trees and subsets
Build interval, tree and subset dynamic programs, including matrix-chain ordering, CYK, rerooting and Held–Karp.
After this lesson you can
- Recognize the interval, tree, subset or DAG structure determining subproblems.
- Solve optimal matrix-chain ordering and optimal binary search tree problems.
- Implement CYK and explain its relation to context-free language parsing.
- Design tree dynamic programs, including rerooting.
- Implement Held–Karp with bitmasks and estimate feasible n.
Before you start
Motivation: three problems, the same question
Three situations arising when building something real:
- Order of an
einsum. With and , expressionnp.einsum('ij,jk,k->i', A, B, x)has two evaluation orders. costs multiplications; costs . With the difference exceeds a factor of two thousand. Three factors are easy to inspect; with twenty tensors of disparate shapes, as in transformer attention or a tensor network, an algorithm must search for the order. This is familiar einsum notation with an algorithmic question underneath. - A language parser. Does a context-free grammar generate a given string? If so, how many ways? The question occurs in formulas, natural language and configurations with ambiguous grammars where deterministic compiler parsers do not work.
- Traveling salesperson with 20 cities. There are distinct cycles visiting the 20 cities. Checking a billion per second would take nearly two years. Held and Karp (and independently Bellman) solved it in 1962 in about steps: less than a second.
All three use dynamic programming, and the difficulty is not the familiar general idea but a prior decision: what is a subproblem? In the previous lesson subproblems were sequence prefixes. Here shape follows problem structure: a product splits into two contiguous products (intervals), a tree into subtrees, and a tour is described by visited cities (subsets).
One question determines the right state in every case: what does the rest of the problem need to know about the solved part? To multiply ‘s result by what follows, only its dimensions matter, not how it was calculated. To decide whether a vertex enters an independent set, its subtree matters only through whether the child is included. To continue a tour, only remaining cities and current position matter, not the order of earlier visits. What the future needs from the past is the state; its size determines the number of subproblems and everything depends on that.
| Structure | Subproblem | States | Transition | Typical cost |
|---|---|---|---|---|
| Sequence (previous lesson) | prefix | or | remove last element | to |
| Interval | contiguous segment | choose split | ||
| Tree | ‘s subtree and a little information about | combine children | ||
| Subset | , sometimes with a distinguished element | or | remove an element |
The first three rows are polynomial; the fourth is not, and that is no defect of the method: nothing substantially better is known for traveling salesperson. At the end, treewidth will measure exactly that, the minimum information size to carry.
Interval dynamic programming
There are segments, each trying up to splits, giving time and memory. The subproblem graph has an edge from to each shorter segment it uses; the natural topological order is by length: all length-1 segments first, then length 2, up to . Ordering by rows with increasing fails, this lesson’s most frequent error: the first interactive shows each cell’s dependencies and why that order reads empty cells.
Matrix-chain multiplication
Multiplying by costs scalar multiplications with the standard algorithm, producing . For a product with , associativity guarantees all parenthesizations produce the same matrix but not the same cost.
Even the smallest example is extreme. With , first forms a matrix and costs operations and numbers of memory; computes a scalar first and costs . With , this is operations and MB in float64 versus operations and no extra memory.
Trying every parenthesization is not an option: their number is Catalan number , growing like (proved in exercises). With 20 matrices there are .
Proof
Every full parenthesization of , with , ends in a final multiplication splitting the chain into for a unique . The first factor is and the second regardless of each internal parenthesization: crucially, final multiplication cost does not depend on how factors were computed. Total cost is left plus right plus , and the first two can be minimized separately: replacing a nonoptimal left parenthesization with an optimal one lowers the total without affecting the rest (cut and paste). Minimizing over gives the recurrence.
For cost, segments of length number , and each tries splits, for total .
∎To recover the parenthesization, store the minimizing split alongside the minimum and reconstruct top-down: split the full product into , each half at its , continuing to individual matrices. This is the same reconstruction pattern as edit distance.
What you should have seen:
- Each cell reads only lower-row cells. Both operands of any candidate lie below the computed cell, on its two triangle slopes. Filling by length, row by row bottom-up, ensures they exist.
- The tree lives in the table. Optimal parenthesization of cell is a binary tree of cells: root , children and , leaves on the bottom row. Optimal subtrees illustrate optimal substructure.
- In the opening example, left-to-right costs and optimum : about 104 times less. Worst parenthesization reaches , 475 times optimum. Matrix is and is : the optimum leaves times until last and keeps all intermediates narrow.
- “Five matrices and a vector” is solved right to left, and “A row vector and five matrices” left to right, with operations instead of . This is matrix–vector versus matrix–matrix multiplication.
The optimal binary search tree
A balanced binary search tree guarantees comparisons per search, but if you know in advance how frequently each key is queried (reserved words sought by a compiler, the most visited prefixes in a routing table), you can do better: frequent keys should be near the root. The tree must still be a search tree: key order cannot change.
The keys of any subtree form a contiguous interval , so this is again an interval problem. Let be the optimal cost for keys (with for the empty interval) and . If the root is , both subtrees hang one level lower, adding one comparison to each search for every key in the interval:
The sum does not depend on , comes out of the minimum and can be obtained in with prefix sums. The cost is again .
Knuth observed in 1971 that the optimal root is monotone: there is a choice of roots with . If cell tests only roots in that range, an entire diagonal takes a telescoping sum, , and the total falls from to . Why the root is monotone, and which general condition on guarantees it, is the Knuth–Yao speedup in the next lesson.
CYK: parsing as dynamic programming
A context-free grammar, type 2 in the Chomsky hierarchy, generates strings by replacing variables with sequences of symbols. Deciding whether it generates a string requires finding a derivation tree, and the structure of those trees is again interval-based if the grammar is in a particular form.
Correctness follows from the same observation as for the matrix chain. In Chomsky normal form, a derivation of an interval of length at least 2 necessarily starts with a rule , and since no variable generates the empty string, generates a nonempty prefix and the rest. Induct on interval length. There are cells, cuts per cell and binary rules per cut: .
By storing in each cell, besides variables, the cuts and rules producing them, the table becomes a shared parse forest: an acyclic graph of size representing all derivation trees at once, even if exponentially many. With the ambiguous grammar , string has as many trees as parenthesizations of four operands. Counting them does not require enumeration: replace “exists” by a sum and “and” by a product in the recurrence. Maxima and products of probabilities yield the best tree of a probabilistic grammar; sums of probabilities yield the total string probability (the inside algorithm). The same table deciding, counting, optimizing and summing is the idea behind dynamic programming over semirings in the next lesson.
Dynamic programming on trees
In a rooted tree, each vertex’s subtree is a natural subproblem: the subtrees of ‘s children are disjoint, there are no edges between them, and the only way out of one is through . All interaction between the solution for and the rest of the tree passes through edge .
The canonical example is maximum-weight independent set: choose vertices with no adjacent pair, maximizing their weight sum . In general graphs it is NP-hard (see the independent set family); on trees it is linear. The state of is a bit: whether it belongs to the set. Call and the best weight of an independent set in that contains or does not. Then
and the answer is at root . If is in, its children cannot be; if it is out, each child chooses whichever is better, and because subtrees do not touch, choices are independent. A complete proof is an exercise. To reconstruct the set, descend from the root: if the parent is in, the child is out; otherwise the child takes the choice reaching its maximum.
What you should have seen in independent-set mode:
- The information going upward is tiny. Two numbers per child. The parent need not know which vertices the child chose, only the weight of the best it can do in each case: that is the boundary discussed in the motivation.
- In the initial tree, the root gives and , so the optimum weighs and includes the root. Node 6, weighing , is excluded despite being among the heaviest: its two children, each weighing , are worth more together. Raise node 6’s weight to and watch the decision cascade.
- The complement of the optimal set is a minimum-weight vertex cover: in the initial tree. A set is independent if and only if touches every edge, so maximizing one’s weight minimizes the other’s. Thus the same dynamic program yields a tree’s minimum cover, or directly use states “ in the cover” (each child chooses its best) and “ out” (all children in).
The same pattern gives the diameter of a tree with nonnegative edge weights. For each , let be the longest descending path from . The longest tree path has a highest vertex , and descends through two distinct children (or just one), so the diameter is the maximum over of the sum of the two largest values among its children. One postorder pass suffices, .
Rerooting: the answer for every root
Many tree questions have no root: the sum of distances from each vertex to all others, each vertex’s eccentricity, the best place for a warehouse. The naive approach roots at every vertex and repeats the dynamic program: times , quadratic. The alternative is linear.
The reference example is weighted distance sum, , with vertex weights (each neighborhood’s population, for instance) and the number of edges in the path. In the first pass, is the weight of and the sum inside the subtree:
because moving up from to makes each vertex of one edge farther away. At the root, . The second pass is one line:
The formula says more. Moving down from to reduces the sum exactly when , so a vertex minimizes if and only if none of the components left by removing it weighs more than half the total. This is the weighted median of a tree (Goldman, 1971), coinciding with the centroid for unit weights. In the interactive, the best root is green: check that it moves toward added weight.
When the summary cannot be “undone” as here, the second pass needs more. For eccentricity (distance to the farthest vertex, with unit-length edges), let be the longest path leaving by first going up to its parent . Then
with ranging over ‘s siblings, convention at the root (and an empty maximum equal to ), and ‘s eccentricity is . The difficulty is the maximum over siblings: maximum has no inverse, so one cannot compute it for all and “remove” . The solution is to store prefix and suffix maxima for ‘s list of children: the maximum excluding is the maximum of the prefix before and suffix after . It remains per vertex and total. This is the general pattern: an associative operation to combine children, a way to add the parent edge, and prefixes and suffixes to exclude a child.
Subsets and bitmasks
When a state must remember an arbitrary set of already-used elements, the number of states is . It is not polynomial, but is much smaller than , and with up to 20 or 25 it fits in memory.
Comparison with pseudopolynomial knapsack is instructive: there the state was remaining capacity, a potentially large number but with a linear structure; here it is a set with no structure allowing compression.
Held–Karp for the traveling salesperson
Let cities have distances , and seek the shortest cycle visiting them all, the traveling salesperson problem. Fix the start at city (every cycle goes through it). For and , let be the length of the shortest path starting at , visiting exactly the cities of and ending at .
Proof
An optimal path for reaches from some city (or from if ), and before that traverses a path from to visiting exactly . That prefix must be optimal for : a shorter one with the same set and endpoint could replace it to give a valid path for , because what can follow depends only on which cities remain and where you are, not the order in which earlier cities were visited. Minimizing over penultimate vertex gives the recurrence. For the cycle, the last leg returns from to .
For cost, each nonempty with each is a state: , each with at most candidates.
∎The replacement argument is the same throughout the lesson, and it works because the order of cities already visited does not matter to the future. This turns paths into states: many past permutations share a state and only the best survives.
What you should have seen:
- A state is a subset plus a final city, and an optimal path is a chain in the lattice adding one city at each step. The state does not remember order: all chains arriving at the same compete, and only the best is kept.
- The initial seven-city optimal cycle measures , and is . Final-city buttons show a tie between and : this is the same cycle traversed backward, which Held–Karp finds twice because distances are symmetric. Drag a city and observe that subset states excluding it do not change: table cells are reusable partial results.
- The curves cross at : exceeds , but is already less than . From there the gap keeps growing. With a day of computing at operations per second, brute force reaches about 16 cities and Held–Karp, in time, about 35; memory runs out much earlier, as the next table shows.
Held–Karp’s practical limit is memory before time:
| operations | table in float32 | ||
|---|---|---|---|
| 16 | 4.2 MB | ||
| 20 | 84 MB | ||
| 24 | 1.6 GB | ||
| 28 | 30 GB |
Each extra city multiplies memory by slightly more than two. Variants retaining only two consecutive size layers reduce the peak, but lose path reconstruction unless recomputed.
Other subset problems
The same technique solves problems unlike the traveling salesperson:
- Minimum-weight perfect matching in a small complete graph with even . Let be the best matching of vertices in . The trick is not to test every pair, but always match the smallest element of : . Since must be matched with someone, no solution is lost; each state tests at most pairs instead of possible pairs, and only subsets produced by always removing the smallest are reached. Cost . Large graphs have polynomial algorithms (Edmonds’), but this fits in ten lines and checks them against a reference.
- Iterating submasks. Many recurrences minimize over all subsets (partitioning a set into groups, coloring a graph). Loop
T = (T - 1) & Svisits the submasks of , and the total over all is by the binomial theorem. This is the cost of directly calculating the chromatic number; Björklund, Husfeldt and Koivisto (2009) reduced it to with inclusion–exclusion.
Beyond: tree decompositions
The lesson’s three structures share a measure: the size of the boundary between what is solved and what remains. In an interval it is two endpoints; in a tree, one vertex; for traveling salesperson, the entire visited set, because in a complete graph any city can go with any other. Treewidth turns that intuition into a number. A tree decomposition of graph is a tree whose nodes are bags of vertices of , such that each vertex and edge of appears in some bag and bags containing a given vertex form a subtree; width is the largest bag size minus one, minimized over all decompositions. Trees have width 1 (one bag per edge), cycles width 2 and complete graph width .
Each bag is a separator: what lies below and above can communicate only through it. Dynamic programming on the decomposition stores, for each bag, a table indexed by its vertices’ states. For maximum independent set, subsets of a bag with vertices give cost : linear in and exponential only in width. This is a textbook example of fixed-parameter tractability, and Courcelle’s theorem generalizes it to any property expressible in monadic second-order logic, with astronomical constants.
Lab 1: contraction order
We start with matrix-chain ordering from scratch, with reconstruction, and compare it against exhaustive search over all parenthesizations for small random chains.
import random
def matrix_chain(p):
"""m[i][j]: coste mínimo de A_i···A_j (índices desde 0); s[i][j]: el corte óptimo."""
n = len(p) - 1
m = [[0] * n for _ in range(n)]
s = [[-1] * n for _ in range(n)]
for L in range(2, n + 1): # POR LONGITUD: m[i][k] y m[k+1][j] ya están calculados
for i in range(n - L + 1):
j = i + L - 1
m[i][j] = float("inf")
for k in range(i, j):
c = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1]
if c < m[i][j]:
m[i][j], s[i][j] = c, k
return m, s
def parenthesize(s, i, j):
if i == j:
return f"A{i + 1}"
k = s[i][j]
return f"({parenthesize(s, i, k)} {parenthesize(s, k + 1, j)})"
def all_costs(p, i, j):
"""Fuerza bruta: el coste de TODOS los parentizados de A_i···A_j (hay C_{j-i} de ellos)."""
if i == j:
return [0]
out = []
for k in range(i, j):
for a in all_costs(p, i, k):
for b in all_costs(p, k + 1, j):
out.append(a + b + p[i] * p[k + 1] * p[j + 1])
return out
random.seed(0)
for n in range(1, 9):
for _ in range(20):
p = [random.randint(1, 60) for _ in range(n + 1)]
m, s = matrix_chain(p)
costs = all_costs(p, 0, n - 1)
assert m[0][n - 1] == min(costs)
print("coincide con la fuerza bruta para n = 1..8 (con n = 8 hay", len(costs), "parentizados)")
p = [100, 1, 100, 4, 20, 100, 1] # el ejemplo inicial del interactivo
m, s = matrix_chain(p)
izq = sum(p[0] * p[k] * p[k + 1] for k in range(1, len(p) - 1))
print("óptimo:", m[0][5], parenthesize(s, 0, 5))
print("de izquierda a derecha:", izq, f"({izq / m[0][5]:.1f} veces más)")
print("peor parentizado:", max(all_costs(p, 0, 5)))The algorithm and enumeration agree on 160 random chains, and the interactive example reproduces its figures: versus , with the worst parenthesization at . Now with actual matrices. Five factors of , , , and , like a chain of layers applied to a vector: we measure each order’s actual time and compare it with choices made by np.linalg.multi_dot, which implements this same dynamic program, and np.einsum_path.
import numpy as np
import time
def evaluate(mats, s, i, j):
"""Multiplica A_i···A_j siguiendo los cortes de s."""
if i == j:
return mats[i]
k = s[i][j]
return evaluate(mats, s, i, k) @ evaluate(mats, s, k + 1, j)
def timeit(f, reps):
t0 = time.perf_counter()
for _ in range(reps):
out = f()
return (time.perf_counter() - t0) / reps, out
p = [600, 40, 600, 30, 600, 1]
rng = np.random.default_rng(0)
mats = [rng.standard_normal((p[k], p[k + 1])) for k in range(len(p) - 1)]
m, s = matrix_chain(p)
izq = sum(p[0] * p[k] * p[k + 1] for k in range(1, len(p) - 1))
print("parentizado óptimo:", parenthesize(s, 0, 4))
print(f"multiplicaciones: óptimo {m[0][4]:,} izquierda a derecha {izq:,} ({izq / m[0][4]:.0f} veces más)")
def left_to_right():
R = mats[0]
for M in mats[1:]:
R = R @ M
return R
t_izq, r_izq = timeit(left_to_right, 2)
t_opt, r_opt = timeit(lambda: evaluate(mats, s, 0, 4), 50)
t_md, r_md = timeit(lambda: np.linalg.multi_dot(mats), 50)
print(f"tiempo: izquierda a derecha {t_izq * 1e3:8.2f} ms")
print(f" orden óptimo {t_opt * 1e3:8.2f} ms ({t_izq / t_opt:.0f} veces menos)")
print(f" np.linalg.multi_dot {t_md * 1e3:8.2f} ms")
print("mismos resultados:", np.allclose(r_izq, r_opt), np.allclose(r_opt, r_md))
path, info = np.einsum_path("ab,bc,cd,de,ef->af", *mats, optimize="optimal")
print("einsum_path:", path)
print([line.strip() for line in info.splitlines() if "FLOP" in line])The optimal order multiplies each matrix by a vector, right to left, doing multiplications instead of more than 36 million. Measured times follow multiplication counts: the measured ratio is of the same order as the theoretical 433, and may be somewhat higher (large products use cache less effectively) or lower (for such small products, fixed call overhead matters). multi_dot finds the same order. The einsum_path path is a list of operand pairs to contract, with each result appended: (3, 4) first, then again the pair in the last two positions, and so leftward. Its printed FLOP count doubles ours because it counts multiplications and additions.
Lab 2: CYK, trees and Held–Karp
First CYK with backpointers to reconstruct a tree, and the version that counts trees instead of deciding.
from collections import defaultdict
# la gramática de expresiones en forma normal de Chomsky del texto
BIN = [("E", "E", "X1"), ("E", "T", "X2"), ("E", "L", "X3"), ("X1", "P", "T"), ("T", "T", "X2"),
("T", "L", "X3"), ("X2", "M", "F"), ("F", "L", "X3"), ("X3", "E", "R")]
TERM = {"a": ["E", "T", "F"], "+": ["P"], "*": ["M"], "(": ["L"], ")": ["R"]}
def cyk(x, BIN, TERM, start="E"):
n = len(x)
T = [[dict() for _ in range(n)] for _ in range(n)] # T[i][j][A] = (k, B, C): cómo se obtuvo A
for i, c in enumerate(x):
for A in TERM.get(c, []):
T[i][i][A] = c
for L in range(2, n + 1): # por longitud de tramo
for i in range(n - L + 1):
j = i + L - 1
for k in range(i, j):
for A, B, C in BIN:
if A not in T[i][j] and B in T[i][k] and C in T[k + 1][j]:
T[i][j][A] = (k, B, C)
return T
def tree(T, i, j, A):
v = T[i][j][A]
if isinstance(v, str):
return v
k, B, C = v
return f"[{A} {tree(T, i, k, B)} {tree(T, k + 1, j, C)}]"
for x in ["a+a*a", "(a+a)*a", "a+*a"]:
T = cyk(x, BIN, TERM)
ok = "E" in T[0][len(x) - 1]
print(f"{x:8s}", "pertenece" if ok else "no pertenece", tree(T, 0, len(x) - 1, "E") if ok else "")
# la gramática ambigua E -> E+E | E*E | a, en forma normal: E -> E Y1 | E Y2, Y1 -> P E, Y2 -> M E
BIN_AMB = [("E", "E", "Y1"), ("E", "E", "Y2"), ("Y1", "P", "E"), ("Y2", "M", "E")]
TERM_AMB = {"a": ["E"], "+": ["P"], "*": ["M"]}
def count_trees(x, BIN, TERM, start="E"):
"""La misma recurrencia con «existe» -> suma y «y» -> producto."""
n = len(x)
N = [[defaultdict(int) for _ in range(n)] for _ in range(n)]
for i, c in enumerate(x):
for A in TERM.get(c, []):
N[i][i][A] += 1
for L in range(2, n + 1):
for i in range(n - L + 1):
j = i + L - 1
for k in range(i, j):
for A, B, C in BIN:
N[i][j][A] += N[i][k][B] * N[k + 1][j][C]
return N[0][n - 1][start]
for operandos in range(2, 12):
x = "+".join(["a"] * operandos)
print(operandos, "operandos:", count_trees(x, BIN_AMB, TERM_AMB), "árboles")With the unambiguous grammar each valid expression has exactly one tree, and string a+*a is rejected. With the ambiguous one, a sum of operands has trees: up to with 11 operands, counted without building any. Next trees, using iterative traversals.
import itertools
import random
import networkx as nx
def orders(n, edges, root=0):
"""Padre de cada vértice y un orden en el que cada vértice va después de su padre (pila explícita)."""
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
order, stack, seen = [], [root], [False] * n
seen[root] = True
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
return parent, order # order al revés es un postorden válido
def max_independent_set(n, edges, w):
parent, order = orders(n, edges)
con, sin = list(w), [0] * n
for u in reversed(order): # hijos antes que padres
p = parent[u]
if p >= 0:
con[p] += sin[u]
sin[p] += max(con[u], sin[u])
chosen = [False] * n
for u in order: # reconstrucción de arriba abajo
p = parent[u]
chosen[u] = False if (p >= 0 and chosen[p]) else con[u] >= sin[u]
return max(con[order[0]], sin[order[0]]), [u for u in range(n) if chosen[u]]
def distance_sums(n, edges, w):
parent, order = orders(n, edges)
W, D = list(w), [0] * n
for u in reversed(order): # primera pasada: subir W y D
p = parent[u]
if p >= 0:
W[p] += W[u]
D[p] += D[u] + W[u]
S = [0] * n
S[order[0]] = D[order[0]]
for u in order[1:]: # segunda pasada: bajar S(c) = S(v) + W - 2 W_c
S[u] = S[parent[u]] + W[order[0]] - 2 * W[u]
return S
def random_tree(n, rng):
return [(v, rng.randrange(v)) for v in range(1, n)]
rng = random.Random(1)
# 1) contra la fuerza bruta en árboles pequeños
for _ in range(200):
n = rng.randint(1, 11)
edges, w = random_tree(n, rng), [rng.randint(0, 9) for _ in range(n)]
best, I = max_independent_set(n, edges, w)
brute = max(sum(w[u] for u in S) for r in range(n + 1) for S in itertools.combinations(range(n), r)
if all(not (a in S and b in S) for a, b in edges))
assert best == brute and sum(w[u] for u in I) == best
assert all(not (a in I and b in I) for a, b in edges)
print("conjunto independiente: coincide con la fuerza bruta en 200 árboles")
# 2) rerooting contra networkx (todas las distancias) en un árbol de 300 vértices
n = 300
edges, w = random_tree(n, rng), [rng.randint(1, 5) for _ in range(n)]
G = nx.Graph(edges)
ref = [sum(w[v] * d for v, d in nx.single_source_shortest_path_length(G, u).items()) for u in range(n)]
S = distance_sums(n, edges, w)
print("rerooting coincide con networkx:", S == ref, "| mediana ponderada:", min(range(n), key=S.__getitem__))
# 3) un camino de 100 000 vértices: la versión recursiva no llega, la iterativa sí
n = 100_000
path_edges = [(v - 1, v) for v in range(1, n)]
def mis_rec(u, parent, adj, w):
con, sin = w[u], 0
for v in adj[u]:
if v != parent:
c, s_ = mis_rec(v, u, adj, w)
con, sin = con + s_, sin + max(c, s_)
return con, sin
adj = [[] for _ in range(n)]
for a, b in path_edges:
adj[a].append(b)
adj[b].append(a)
try:
mis_rec(0, -1, adj, [1] * n)
except RecursionError as e:
print("recursiva:", type(e).__name__)
best, _ = max_independent_set(n, path_edges, [1] * n)
print("iterativa:", best, "(la mitad de los vértices, como debe ser en un camino)")Finally, vectorized Held–Karp. The key to NumPy performance is processing all same-size subsets containing simultaneously: for them, is the row minimum of a matrix dp[S ^ (1 << j)] + D[:, j]. Here masks include city (bit 0 always set), using twice the memory in exchange for simpler code.
import itertools
import time
import numpy as np
import networkx as nx
def held_karp(D):
D = np.asarray(D, dtype=np.float64)
n = len(D)
N = 1 << n
dp = np.full((N, n), np.inf)
par = np.full((N, n), -1, dtype=np.int8)
dp[1, 0] = 0.0 # solo la ciudad 0, estamos en 0
masks = np.arange(N)
pc = sum((masks >> b) & 1 for b in range(n)) # tamaño de cada subconjunto
for size in range(2, n + 1):
layer = masks[(pc == size) & (masks & 1 == 1)]
for j in range(1, n):
S = layer[(layer >> j) & 1 == 1] # subconjuntos de este tamaño que contienen a j
cand = dp[S ^ (1 << j)] + D[:, j] # una fila por S, una columna por penúltima ciudad i
i_best = np.argmin(cand, axis=1)
par[S, j] = i_best
dp[S, j] = cand[np.arange(len(S)), i_best]
full = N - 1
last = int(np.argmin(dp[full] + D[:, 0]))
tour, S, j = [], full, last
while j != 0:
tour.append(j)
S, j = S ^ (1 << j), int(par[S, j])
return dp[full, last] + D[last, 0], [0] + tour[::-1]
def tour_length(D, t):
return sum(D[t[k], t[(k + 1) % len(t)]] for k in range(len(t)))
rng = np.random.default_rng(0)
# 1) contra la fuerza bruta (8! = 40 320 permutaciones) con n = 9
P = rng.random((9, 2))
D = np.linalg.norm(P[:, None] - P[None], axis=-1)
perms = np.array(list(itertools.permutations(range(1, 9))))
cyc = np.hstack([np.zeros((len(perms), 1), int), perms, np.zeros((len(perms), 1), int)])
brute = D[cyc[:, :-1], cyc[:, 1:]].sum(axis=1).min()
best, tour = held_karp(D)
print(f"n = 9: Held-Karp {best:.6f}, fuerza bruta {brute:.6f}, ciclo {tour}, longitud {tour_length(D, tour):.6f}")
# 2) tiempos y memoria
for n in [10, 12, 14, 16, 18]:
P = rng.random((n, 2))
D = np.linalg.norm(P[:, None] - P[None], axis=-1)
t0 = time.perf_counter()
held_karp(D)
t = time.perf_counter() - t0
print(f"n = {n:2d}: {t:6.3f} s tabla {(1 << n) * n * 8 / 2**20:6.1f} MiB 2^n n^2 = {2**n * n * n:.1e}")
# 3) emparejamiento perfecto de peso mínimo en O(2^n n), contra networkx
def min_perfect_matching(Wm):
n = len(Wm)
f = {0: 0.0}
def solve(S):
if S in f:
return f[S]
i = (S & -S).bit_length() - 1 # el menor elemento de S tiene que emparejarse
rest = S & ~(1 << i)
best = np.inf
T = rest
while T:
j = (T & -T).bit_length() - 1
T &= T - 1
best = min(best, Wm[i][j] + solve(rest & ~(1 << j)))
f[S] = best
return best
return solve((1 << n) - 1), len(f)
for n in [6, 10, 14]:
P = rng.random((n, 2))
Wm = np.linalg.norm(P[:, None] - P[None], axis=-1).tolist()
val, states = min_perfect_matching(Wm)
G = nx.complete_graph(n)
for u, v in G.edges:
G[u][v]["weight"] = Wm[u][v]
M = nx.min_weight_matching(G)
ref = sum(Wm[u][v] for u, v in M)
print(f"emparejamiento n = {n:2d}: máscaras {val:.6f}, networkx {ref:.6f}, estados visitados {states} de {2**n}")Three things to notice in the output. Held–Karp agrees with the permutations. With few cities NumPy’s fixed per-call cost dominates, but from time multiplies four or five times every two cities, near the factor predicted by , ; the float64 table including city ‘s bit uses bytes. Mask matching agrees with networkx’s blossom algorithm while visiting far fewer of the possible states: always removing the smallest element reaches only subsets obtainable that way.
The professional version
- Matrix chains:
np.linalg.multi_dot(mats)applies this lesson’s recurrence (with a closed formula for three factors). Use it whenever chaining more than two products with different shapes. - General contractions:
np.einsum(..., optimize="optimal")oroptimize="greedy", andnp.einsum_pathto see the plan before running it. With many operands,opt_einsum(used underneath by PyTorch and JAX for theireinsum) offers more scalable strategies. Compute the path once and reuse it if shapes do not change. - Grammars: CYK is the theoretical reference, but real general parsers use Earley’s algorithm or GLR on the original grammar without normal-form conversion; Earley costs in the worst case and on unambiguous grammars. For probabilistic grammars, CYK with maxima and products remains the standard algorithm.
- Traveling salesperson: OR-Tools, or Concorde for certified optima. Held–Karp makes sense for and as a piece of other algorithms, for example to optimize short tour segments exactly.
- Matching:
networkx.min_weight_matchingandmax_weight_matchingimplement Edmonds’ blossom algorithm;scipy.optimize.linear_sum_assignmentsolves the bipartite case.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What recurrence does satisfy?
optimal_bst(p). p is a list of frequencies for keys , in order. Return a pair (coste, arbol): the minimum cost and a tree attaining it, as nested tuples (clave, izquierdo, derecho) with None for an empty tree. With p = [] return (0, None). Tests compare against all possible trees for .def optimal_bst(p):
n = len(p)
# e[i][j]: coste óptimo con las claves i..j-1 (tramos semiabiertos); root[i][j]: la raíz que lo alcanza
# e[i][j] = min_r (e[i][r] + e[r + 1][j]) + p[i] + ... + p[j - 1]
passStep 1 of 5. What property of trees ensures choices in different children do not interfere?
More than one answer may be correct.
Summary
- Intervals. from shorter intervals, in length order. Matrix-chain ordering, , costs versus parenthesizations, and choosing well can save orders of magnitude; backpropagation is its special case with a row vector at the start. Optimal search trees use the same recurrence with a root instead of a cut, and Knuth monotonicity reduces it to .
- CYK decides whether a Chomsky-normal-form grammar generates a string in , and the same table counts trees or finds the most likely by changing operations. Conversion expands the grammar: binarize before eliminating empty rules.
- Trees. A few values per vertex, computed in postorder and without recursion in Python: weighted independent set and vertex cover, diameter. Rerooting gives the answer for every root in with a second pass correcting what changes across each edge, as in .
- Subsets. Bitmasks traversed in increasing order. Held–Karp solves traveling salesperson in time and memory, feasible up to if memory is calculated first; minimum perfect matching costs by always matching the smallest element.