Module contents
Lesson 16 of 33Advanced 115 min

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 A,B∈Rn×n\mat{A}, \mat{B} \in \R^{n\times n} and x∈Rn\vb{x} \in \R^n, expression np.einsum('ij,jk,k->i', A, B, x) has two evaluation orders. (AB)x(\mat{A}\mat{B})\vb{x} costs n3+n2n^3 + n^2 multiplications; A(Bx)\mat{A}(\mat{B}\vb{x}) costs 2n22n^2. With n=4096n = 4096 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 19!/2≈6.08⋅101619!/2 \approx 6.08\cdot 10^{16} 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 220⋅202≈4.2⋅1082^{20}\cdot 20^2 \approx 4.2\cdot 10^8 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 Ai⋯Ak\mat{A}_i\cdots\mat{A}_k‘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.

StructureSubproblemStatesTransitionTypical cost
Sequence (previous lesson)prefix x1…xix_1\dots x_inn or nmnmremove last elementO(n)\bigO(n) to O(nm)\bigO(nm)
Intervalcontiguous segment [i,j][i, j]Θ(n2)\Theta(n^2)choose split kkO(n3)\bigO(n^3)
Treevv‘s subtree and a little information about vvO(n)\bigO(n)combine childrenO(n)\bigO(n)
SubsetS⊆US \subseteq U, sometimes with a distinguished element2n2^n or 2nn2^n nremove an elementO(2nn2)\bigO(2^n n^2)

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 (n2)+n=n(n+1)/2\binom{n}{2} + n = n(n+1)/2 segments, each trying up to n−1n - 1 splits, giving O(n3)\bigO(n^3) time and Θ(n2)\Theta(n^2) memory. The subproblem graph has an edge from [i,j][i, j] to each shorter segment it uses; the natural topological order is by length: all length-1 segments first, then length 2, up to [1,n][1, n]. Ordering by rows with increasing ii 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 A∈Rp×q\mat{A} \in \R^{p\times q} by B∈Rq×r\mat{B} \in \R^{q\times r} costs pqrpqr scalar multiplications with the standard algorithm, producing p×rp\times r. For a product A1A2⋯An\mat{A}_1\mat{A}_2\cdots\mat{A}_n with Ak∈Rpk−1×pk\mat{A}_k \in \R^{p_{k-1}\times p_k}, associativity guarantees all parenthesizations produce the same matrix but not the same cost.

Even the smallest example is extreme. With u,v,w∈Rn\vb{u}, \vb{v}, \vb{w} \in \R^n, (uv⊤)w(\vb{u}\vb{v}\T)\vb{w} first forms a matrix n×nn\times n and costs 2n22n^2 operations and n2n^2 numbers of memory; u(v⊤w)\vb{u}(\vb{v}\T\vb{w}) computes a scalar first and costs 2n2n. With n=104n = 10^4, this is 2⋅1082\cdot 10^8 operations and 800800 MB in float64 versus 2⋅1042\cdot 10^4 operations and no extra memory.

Trying every parenthesization is not an option: their number is Catalan number Cn−1C_{n-1}, growing like 4n/n3/24^n/n^{3/2} (proved in exercises). With 20 matrices there are C19≈1.77⋅109C_{19} \approx 1.77\cdot 10^9.

Proof

Every full parenthesization of Ai⋯Aj\mat{A}_i\cdots\mat{A}_j, with i<ji < j, ends in a final multiplication splitting the chain into (Ai⋯Ak)(Ak+1⋯Aj)(\mat{A}_i\cdots\mat{A}_k)(\mat{A}_{k+1}\cdots\mat{A}_j) for a unique k∈[i,j−1]k \in [i, j-1]. The first factor is pi−1×pkp_{i-1}\times p_k and the second pk×pjp_k\times p_j regardless of each internal parenthesization: crucially, final multiplication cost pi−1pkpjp_{i-1}p_kp_j does not depend on how factors were computed. Total cost is left plus right plus pi−1pkpjp_{i-1}p_kp_j, 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 kk gives the recurrence.

For cost, segments of length LL number n−L+1n - L + 1, and each tries L−1L - 1 splits, for total ∑L=2n(n−L+1)(L−1)=(n+13)=(n3−n)/6\sum_{L=2}^{n} (n - L + 1)(L - 1) = \binom{n+1}{3} = (n^3 - n)/6.

∎

To recover the parenthesization, store the minimizing split s[i,j]s[i, j] alongside the minimum and reconstruct top-down: split the full product into s[1,n]s[1, n], each half at its ss, continuing to individual matrices. This is the same reconstruction pattern as edit distance.

InteractiveThe matrix-chain triangle
Cell (i, j) = minimum cost of Aᵢ···Aⱼ, drawn over its matrix segmentℓ = 2ℓ = 3ℓ = 4ℓ = 5ℓ = 6A1A2A3A4A5A610.0k40080008000200080048048.0k208024802480248012.5k24842584100×11×100100×44×2020×100100×1
cell (1, 6), ℓ = 6
Candidates for m[1,6]=min⁡k m[1,k]+m[k+1,6]+p0 pk p6m[1, 6] = \min_k\, m[1, k] + m[k+1, 6] + p_{0}\,p_k\,p_{6}
k = 1: A1..1 | 2..62 584 ←
k = 2: A1..2 | 3..622 480
k = 3: A1..3 | 4..63 280
k = 4: A1..4 | 5..66 480
k = 5: A1..5 | 6..622 480
0 + 2 484 + 100·1·1 = 2 584(the minimum)
Chain dimensions
100
1
100
4
20
100
1
Optimal cost m[1, 6]2 584
Left to right268 000
Left to right / optimum104×
Worst parenthesization1 228 000
Possible parenthesizationsC₅ = 42
Optimum: A1((A2A3)(A4(A5A6)))A_{1}((A_{2}A_{3})(A_{4}(A_{5}A_{6}))). Multiplying left to right costs 104 times as much.
Table mm rotated 45°: cell (i,j)(i, j) sits above matrix segment Ai⋯Aj\mat{A}_i\cdots\mat{A}_j and each horizontal row is a length ℓ\ell. Clicking a cell shows candidates kk (left orange, right aquamarine, final multiplication purple) and its parenthesization tree, whose internal nodes are cells of the triangle. Hover over nonminimum candidates to see the tree change. Play from the start to see fill order.

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 (1,6)(1, 6) is a binary tree of cells: root (1,6)(1, 6), children (1,s)(1, s) and (s+1,6)(s+1, 6), leaves on the bottom row. Optimal subtrees illustrate optimal substructure.
  • In the opening example, left-to-right costs 268 000268\,000 and optimum 2 5842\,584: about 104 times less. Worst parenthesization reaches 1 228 0001\,228\,000, 475 times optimum. Matrix A1\mat{A}_1 is 100×1100\times 1 and A6\mat{A}_6 is 100×1100\times 1: the optimum leaves 100×1100\times 1 times 1×11\times 1 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 50 00050\,000 operations instead of 4 010 0004\,010\,000. This is matrix–vector versus matrix–matrix multiplication.

The optimal binary search tree

A balanced binary search tree guarantees O(log⁡n)\bigO(\log n) 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 ki,…,kjk_i, \dots, k_j, so this is again an interval problem. Let e[i,j]e[i, j] be the optimal cost for keys ki,…,kjk_i, \dots, k_j (with e[i,i−1]=0e[i, i-1] = 0 for the empty interval) and w(i,j)=pi+⋯+pjw(i, j) = p_i + \dots + p_j. If the root is krk_r, both subtrees hang one level lower, adding one comparison to each search for every key in the interval:

e[i,j]=min⁡i≤r≤j(e[i,r−1]+e[r+1,j])+w(i,j).e[i, j] = \min_{i \le r \le j} \Big( e[i, r-1] + e[r+1, j] \Big) + w(i, j).

The sum w(i,j)w(i, j) does not depend on rr, comes out of the minimum and can be obtained in O(1)\bigO(1) with prefix sums. The cost is again Θ(n3)\Theta(n^3).

Knuth observed in 1971 that the optimal root is monotone: there is a choice of roots with raıˊz⁡[i,j−1]≤raıˊz⁡[i,j]≤raıˊz⁡[i+1,j]\operatorname{raíz}[i, j-1] \le \operatorname{raíz}[i, j] \le \operatorname{raíz}[i+1, j]. If cell [i,j][i, j] tests only roots in that range, an entire diagonal takes a telescoping sum, ∑i(raıˊz⁡[i+1,j]−raıˊz⁡[i,j−1]+1)≤2n\sum_i \big(\operatorname{raíz}[i+1, j] - \operatorname{raíz}[i, j-1] + 1\big) \le 2n, and the total falls from Θ(n3)\Theta(n^3) to Θ(n2)\Theta(n^2). Why the root is monotone, and which general condition on c(i,k,j)c(i, k, j) 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 x=x1⋯xnx = x_1\cdots x_n 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 A→BCA \to BC, and since no variable generates the empty string, BB generates a nonempty prefix xi⋯xkx_i\cdots x_k and CC the rest. Induct on interval length. There are Θ(n2)\Theta(n^2) cells, O(n)\bigO(n) cuts per cell and ∣R∣\abs{R} binary rules per cut: O(n3∣R∣)\bigO(n^3\abs{R}).

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 O(n3∣R∣)\bigO(n^3\abs{R}) representing all derivation trees at once, even if exponentially many. With the ambiguous grammar E→E+E∣E∗E∣aE \to E + E \mid E * E \mid a, string a+a∗a+aa + a * a + a 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 TvT_v is a natural subproblem: the subtrees of vv‘s children are disjoint, there are no edges between them, and the only way out of one is through vv. All interaction between the solution for TcT_c and the rest of the tree passes through edge (v,c)(v, c).

The canonical example is maximum-weight independent set: choose vertices with no adjacent pair, maximizing their weight sum wv≥0w_v \ge 0. In general graphs it is NP-hard (see the independent set family); on trees it is linear. The state of vv is a bit: whether it belongs to the set. Call con⁡(v)\operatorname{con}(v) and sin⁡(v)\operatorname{sin}(v) the best weight of an independent set in TvT_v that contains vv or does not. Then

con⁡(v)=wv+∑c hijo de vsin⁡(c),sin⁡(v)=∑c hijo de vmax⁡(con⁡(c),sin⁡(c)),\operatorname{con}(v) = w_v + \sum_{c \text{ hijo de } v} \operatorname{sin}(c), \qquad \operatorname{sin}(v) = \sum_{c \text{ hijo de } v} \max\big(\operatorname{con}(c), \operatorname{sin}(c)\big),

and the answer is max⁡(con⁡(r),sin⁡(r))\max(\operatorname{con}(r), \operatorname{sin}(r)) at root rr. If vv 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.

InteractiveValues moving up and down a tree
Below each node, best subtree weight: in (blue) | out (violet)30222141472286535664601510565627204840393031030
reconstruction
Root 0: max⁡(in,out)=max⁡(22,21)=22\max(\text{in}, \text{out}) = \max(22, 21) = 22. Reconstruct top-down: if the parent is in the set, the child is out; otherwise the child takes the maximizing option.
Dynamic programming
Selected node: 0
3
Maximum independent set weight22
Minimum vertex cover16
Total weight38
Subsets examined by brute force2048
Set: {0,4,5,7,8,9,10}\{0, 4, 5, 7, 8, 9, 10\}. Its complement is a minimum-weight vertex cover.
Each node shows its weight. In Independent Set mode, the animation traverses the tree in postorder and sends each child's (with, without) pair to its parent; finally the optimal set is reconstructed in blue. In Rerooting mode, a first pass sends subtree weight WW and its internal distance sum DD upward, and a second sends the answer SS from parent to child; bars show the answer for each possible root. Edit the tree: select a node, change its weight, add children or root the tree there.

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 con⁡=22\operatorname{con} = 22 and sin⁡=21\operatorname{sin} = 21, so the optimum weighs 2222 and includes the root. Node 6, weighing 55, is excluded despite being among the heaviest: its two children, each weighing 33, are worth more together. Raise node 6’s weight to 77 and watch the decision cascade.
  • The complement of the optimal set is a minimum-weight vertex cover: 38−22=1638 - 22 = 16 in the initial tree. A set II is independent if and only if V∖IV\setminus I 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 “vv in the cover” (each child chooses its best) and “vv out” (all children in).

The same pattern gives the diameter of a tree with nonnegative edge weights. For each vv, let h(v)h(v) be the longest descending path from vv. The longest tree path has a highest vertex vv, and descends through two distinct children (or just one), so the diameter is the maximum over vv of the sum of the two largest values h(c)+w(v,c)h(c) + w(v, c) among its children. One postorder pass suffices, O(n)\bigO(n).

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: nn times O(n)\bigO(n), quadratic. The alternative is linear.

The reference example is weighted distance sum, S(v)=∑uwu d(u,v)S(v) = \sum_u w_u\,d(u, v), with vertex weights wu≥0w_u \ge 0 (each neighborhood’s population, for instance) and dd the number of edges in the path. In the first pass, WvW_v is the weight of TvT_v and Dv=∑u∈Tvwu d(u,v)D_v = \sum_{u\in T_v} w_u\,d(u, v) the sum inside the subtree:

Wv=wv+∑cWc,Dv=∑c(Dc+Wc),W_v = w_v + \sum_{c} W_c, \qquad D_v = \sum_{c} \big(D_c + W_c\big),

because moving up from cc to vv makes each vertex of TcT_c one edge farther away. At the root, S(r)=DrS(r) = D_r. The second pass is one line:

S(c)−S(v)=∑uwu ΔuS(c) - S(v) = \sum_{u} w_u\,\Delta_u
With Δu=d(u,c)−d(u,v)\Delta_u = d(u, c) - d(u, v): subtract the sums term by term, and cc is a child of vv.
1/4

The formula says more. Moving down from vv to cc reduces the sum exactly when Wc>W/2W_c > W/2, so a vertex minimizes SS 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 up⁡(c)\operatorname{up}(c) be the longest path leaving cc by first going up to its parent vv. Then

up⁡(c)=1+max⁡(up⁡(v), max⁡c′≠c(1+h(c′))),\operatorname{up}(c) = 1 + \max\Big(\operatorname{up}(v),\ \max_{c' \ne c} \big(1 + h(c')\big)\Big),

with c′c' ranging over cc‘s siblings, convention up⁡(r)=0\operatorname{up}(r) = 0 at the root (and an empty maximum equal to 00), and cc‘s eccentricity is max⁡(up⁡(c),h(c))\max(\operatorname{up}(c), h(c)). The difficulty is the maximum over siblings: maximum has no inverse, so one cannot compute it for all and “remove” cc. The solution is to store prefix and suffix maxima for vv‘s list of children: the maximum excluding cc is the maximum of the prefix before and suffix after cc. It remains O(deg⁡v)\bigO(\deg v) per vertex and O(n)\bigO(n) 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 2n2^n. It is not polynomial, but 2n2^n is much smaller than n!n!, and with nn 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 nn cities 0,…,n−10, \dots, n-1 have distances d(i,j)d(i, j), and seek the shortest cycle visiting them all, the traveling salesperson problem. Fix the start at city 00 (every cycle goes through it). For S⊆{1,…,n−1}S \subseteq \{1, \dots, n-1\} and j∈Sj \in S, let g(S,j)g(S, j) be the length of the shortest path starting at 00, visiting exactly the cities of SS and ending at jj.

Proof

An optimal path for (S,j)(S, j) reaches jj from some city i∈S∖{j}i \in S\setminus\{j\} (or from 00 if S={j}S = \{j\}), and before that traverses a path from 00 to ii visiting exactly S∖{j}S\setminus\{j\}. That prefix must be optimal for (S∖{j},i)(S\setminus\{j\}, i): a shorter one with the same set and endpoint could replace it to give a valid path for (S,j)(S, j), 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 ii gives the recurrence. For the cycle, the last leg returns from jj to 00.

For cost, each nonempty SS with each j∈Sj \in S is a state: ∑k=1n−1k(n−1k)=(n−1) 2n−2\sum_{k=1}^{n-1} k\binom{n-1}{k} = (n-1)\,2^{n-2}, each with at most n−2n - 2 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 (n−1)!(n-1)! paths into (n−1) 2n−2(n-1)\,2^{n-2} states: many past permutations share a state and only the best survives.

InteractiveThe Held–Karp lattice
State (S,j)(S, j) with S={1,2,3,4,5,6}S = \{1, 2, 3, 4, 5, 6\}, j=3j = 3: the best path 0→5→1→6→2→4→30 \to 5 \to 1 \to 6 \to 2 \to 4 \to 3 has length 17.8517.85; closing the tour with d(3,0)=4.57d(3, 0) = 4.57 yields 22.4222.42.
(closed tour length)
Lattice of subsets S ⊆ {1, …, 6} by size: 63 subsets, 192 states (S, j)|S| = 1|S| = 2|S| = 3|S| = 4|S| = 5|S| = 6{1}{2}{3}{4}{5}{6}{1, 2}{1, 3}{2, 3}{1, 4}{2, 4}{3, 4}{1, 5}{2, 5}{3, 5}{4, 5}{1, 6}{2, 6}{3, 6}{4, 6}{5, 6}{1, 2, 3}{1, 2, 4}{1, 3, 4}{2, 3, 4}{1, 2, 5}{1, 3, 5}{2, 3, 5}{1, 4, 5}{2, 4, 5}{3, 4, 5}{1, 2, 6}{1, 3, 6}{2, 3, 6}{1, 4, 6}{2, 4, 6}{3, 4, 6}{1, 5, 6}{2, 5, 6}{3, 5, 6}{4, 5, 6}{1, 2, 3, 4}{1, 2, 3, 5}{1, 2, 4, 5}{1, 3, 4, 5}{2, 3, 4, 5}{1, 2, 3, 6}{1, 2, 4, 6}{1, 3, 4, 6}{2, 3, 4, 6}{1, 2, 5, 6}{1, 3, 5, 6}{2, 3, 5, 6}{1, 4, 5, 6}{2, 4, 5, 6}{3, 4, 5, 6}{1, 2, 3, 4, 5}{1, 2, 3, 4, 6}{1, 2, 3, 5, 6}{1, 2, 4, 5, 6}{1, 3, 4, 5, 6}{2, 3, 4, 5, 6}{1, 2, 3, 4, 5, 6}selected: S = {1, 2, 3, 4, 5, 6}, j = 3Operations (log scale): brute force n! versus Held–Karp 2ⁿn²110¹⁰10²⁰10³⁰10⁴⁰10⁹ ≈ 1 s≈ 1 day5101520253035nn!2ⁿn²n = 7
Cities n7
Optimal tour22.42
States (S, j): (n−1)·2ⁿ⁻²192
Held–Karp work ≈ 2ⁿn²6 272
Distinct tours (n−1)!/2360
n!5 040
With n=20n = 20: 220⋅202≈4.19⋅1082^{20}\cdot 20^2 \approx 4.19\cdot 10^{8} operations versus 19!/2≈6.08⋅101619!/2 \approx 6.08\cdot 10^{16} distinct tours.
Above are the cities: drag them, or click the map background to add one (up to eight). Below are all subsets S⊆{1,…,n−1}S \subseteq \{1, \dots, n-1\} ordered by size, with a line between each subset and those with one more element. Choose a subset and final city jj: the map draws the best path for state (S,j)(S, j) and the lattice lights up its chain of subsets, one per city added. At the bottom, growth of 2nn22^n n^2 versus n!n! on a logarithmic scale, with your nn marked.

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 (S,j)(S, j) compete, and only the best is kept.
  • The initial seven-city optimal cycle measures 22.4222.42, and is 0→5→1→6→2→4→3→00 \to 5 \to 1 \to 6 \to 2 \to 4 \to 3 \to 0. Final-city buttons show a tie between j=3j = 3 and j=5j = 5: 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 n=8n = 8: 27⋅72=6 2722^7\cdot 7^2 = 6\,272 exceeds 7!=5 0407! = 5\,040, but 28⋅82=16 3842^8\cdot 8^2 = 16\,384 is already less than 8!=40 3208! = 40\,320. From there the gap keeps growing. With a day of computing at 10910^9 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:

nnoperations 2nn22^n n^2table 2n⋅n2^n\cdot n in float32n!n!
161.7⋅1071.7\cdot 10^74.2 MB2.1⋅10132.1\cdot 10^{13}
204.2⋅1084.2\cdot 10^884 MB2.4⋅10182.4\cdot 10^{18}
249.7⋅1099.7\cdot 10^91.6 GB6.2⋅10236.2\cdot 10^{23}
282.1⋅10112.1\cdot 10^{11}30 GB3.0⋅10293.0\cdot 10^{29}

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 nn. Let f(S)f(S) be the best matching of vertices in SS. The trick is not to test every pair, but always match the smallest element ii of SS: f(S)=min⁡j∈S,j≠i(w(i,j)+f(S∖{i,j}))f(S) = \min_{j \in S, j \ne i} \big(w(i, j) + f(S\setminus\{i, j\})\big). Since ii must be matched with someone, no solution is lost; each state tests at most n−1n - 1 pairs instead of (∣S∣2)\binom{\abs{S}}{2} possible pairs, and only subsets produced by always removing the smallest are reached. Cost O(2nn)\bigO(2^n n). 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 T⊆ST \subseteq S (partitioning a set into groups, coloring a graph). Loop T = (T - 1) & S visits the 2∣S∣2^{\abs{S}} submasks of SS, and the total over all SS is ∑S2∣S∣=3n\sum_S 2^{\abs{S}} = 3^n by the binomial theorem. This is the cost of directly calculating the chromatic number; Björklund, Husfeldt and Koivisto (2009) reduced it to O∗(2n)\bigO^*(2^n) 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 GG is a tree whose nodes are bags of vertices of GG, such that each vertex and edge of GG 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 KnK_n width n−1n - 1.

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, 2k+12^{k+1} subsets of a bag with k+1k + 1 vertices give cost O(2kkO(1)n)\bigO(2^k k^{\bigO(1)} n): linear in nn 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.

[ ]Matrix-chain ordering from scratch versus brute forceBrowser
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: 2 5842\,584 versus 268 000268\,000, with the worst parenthesization at 1 228 0001\,228\,000. Now with actual matrices. Five factors of 600×40600\times 40, 40×60040\times 600, 600×30600\times 30, 30×60030\times 600 and 600×1600\times 1, 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.

[ ]Measured times, multi_dot and einsum_pathBrowser
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 84 00084\,000 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.

[ ]CYK: recognize, reconstruct and countBrowser
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 mm operands has Cm−1C_{m-1} trees: 1,2,5,14,42,…1, 2, 5, 14, 42, \dots up to 16 79616\,796 with 11 operands, counted without building any. Next trees, using iterative traversals.

[ ]Independent set and rerooting without recursionBrowser
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 jj simultaneously: for them, g(S,j)g(S, j) is the row minimum of a matrix dp[S ^ (1 << j)] + D[:, j]. Here masks include city 00 (bit 0 always set), using twice the memory in exchange for simpler code.

[ ]Held–Karp with NumPy masks, and matchingBrowser
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 40 32040\,320 permutations. With few cities NumPy’s fixed per-call cost dominates, but from n=14n = 14 time multiplies four or five times every two cities, near the factor predicted by 2nn22^n n^2, 4(n+2)2/n2≈54(n+2)^2/n^2 \approx 5; the float64 table including city 00‘s bit uses 2n⋅n⋅82^n\cdot n\cdot 8 bytes. Mask matching agrees with networkx’s blossom algorithm while visiting far fewer of the 2n2^n 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") or optimize="greedy", and np.einsum_path to see the plan before running it. With many operands, opt_einsum (used underneath by PyTorch and JAX for their einsum) 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 O(n3)\bigO(n^3) in the worst case and O(n2)\bigO(n^2) 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 n≤20n \le 20 and as a piece of other algorithms, for example to optimize short tour segments exactly.
  • Matching: networkx.min_weight_matching and max_weight_matching implement Edmonds’ blossom algorithm; scipy.optimize.linear_sum_assignment solves the bipartite case.

Common mistakes

Exercises

NumericThree matrices
Calculate the minimum number of scalar multiplications needed to compute A1A2A3\mat{A}_1\mat{A}_2\mat{A}_3, with dimensions 10×3010\times 30, 30×530\times 5 and 5×605\times 60.
QuizWhat fill order works?
An interval dynamic program computes f(i,j)f(i, j) from f(i,k)f(i, k) and f(k+1,j)f(k+1, j) with i≤k<ji \le k < j, storing values in a table. Which computation orders are correct?

More than one answer may be correct.

ProofHow many parenthesizations?
Prove: Let PnP_n be the number of full parenthesizations of a product of n≥1n \ge 1 matrices. Then Pn=Cn−1P_n = C_{n-1}, the Catalan number, and Pn≥2n−2P_n \ge 2^{n-2} for n≥2n \ge 2: trying all is exponential.
0
Recall that Catalan numbers satisfy C0=1C_0 = 1 and Cm=∑i=0m−1Ci Cm−1−iC_m = \sum_{i=0}^{m-1} C_i\,C_{m-1-i}.

Step 1 of 4. What recurrence does PnP_n satisfy?

CodeOptimal search tree with reconstruction
Implement optimal_bst(p). p is a list of frequencies for keys 0,…,n−10, \dots, n-1, in order. Return a pair (coste, arbol): the minimum cost ∑tpt (prof(t)+1)\sum_t p_t\,(\text{prof}(t) + 1) 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 n≤8n \le 8.
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]
  pass
Shift+Enter to run
NumericTrees of an ambiguous expression
With the ambiguous grammar E→E+E∣E∗E∣aE \to E + E \mid E * E \mid a, how many distinct derivation trees does the string a+a∗a+aa + a * a + a have?
ProofCorrectness of independent set on trees
Prove: In a rooted tree with weights wv≥0w_v \ge 0, let con(v)\text{con}(v) and sin(v)\text{sin}(v) be the maximum weight of an independent set of subtree TvT_v that contains vv or does not. Then con(v)=wv+∑csin(c)\text{con}(v) = w_v + \sum_c \text{sin}(c) and sin(v)=∑cmax⁡(con(c),sin(c))\text{sin}(v) = \sum_c \max(\text{con}(c), \text{sin}(c)), summing over children cc of vv.
0
Use structural induction on the tree: assume the result holds for subtrees of the children of vv. Prove both inequalities for each equality.

Step 1 of 5. What property of trees ensures choices in different children do not interfere?

NumericOne rerooting step
A tree has 20 vertices of weight 1. The sum of distances from vertex vv to all others is S(v)=47S(v) = 47. A child cc of vv has a subtree of 6 vertices (counting cc). What is S(c)S(c)?
QuizHeld–Karp with 25 cities
You want to run Held–Karp with n=25n = 25 cities, storing the complete table g[S][j]g[S][j], with SS ranging over all 2252^{25} subsets of the 25 cities and jj over the 25 cities, in float32 (4 bytes). Does it fit in 32 GB of RAM?
QuizHow many states are needed?
For which problems is there a natural dynamic program with a polynomial number of states (in input size, without assuming P = NP)?

More than one answer may be correct.

Summary

Key idea
The shape of subproblems is dictated by what the rest of the problem needs to know about the solved part. For an interval its endpoints suffice; for a subtree, its root: Θ(n2)\Theta(n^2) and Θ(n)\Theta(n) states, polynomial dynamic programs. For traveling salesperson the whole visited set must be remembered: 2n2^n states, exponential but much better than n!n!. Treewidth measures this boundary size in general.
  • Intervals. f(i,j)f(i, j) from shorter intervals, in length order. Matrix-chain ordering, m[i,j]=min⁡km[i,k]+m[k+1,j]+pi−1pkpjm[i, j] = \min_k m[i, k] + m[k+1, j] + p_{i-1}p_kp_j, costs Θ(n3)\Theta(n^3) versus Cn−1C_{n-1} 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 Θ(n2)\Theta(n^2).
  • CYK decides whether a Chomsky-normal-form grammar generates a string in O(n3∣R∣)\bigO(n^3\abs{R}), 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 O(n)\bigO(n) with a second pass correcting what changes across each edge, as in S(c)=S(v)+W−2WcS(c) = S(v) + W - 2W_c.
  • Subsets. Bitmasks traversed in increasing order. Held–Karp solves traveling salesperson in O(2nn2)\bigO(2^n n^2) time and O(2nn)\bigO(2^n n) memory, feasible up to n≈25n \approx 25 if memory is calculated first; minimum perfect matching costs O(2nn)\bigO(2^n n) by always matching the smallest element.