Advanced dynamic programming: semirings and speed-ups
Unify dynamic programs with semirings and accelerate transitions using monotone queues, convex hulls, divide and conquer, Knuth–Yao and SMAWK.
After this lesson you can
- Reformulate dynamic programs over semirings and exchange the semiring to obtain variants.
- Compute linear recurrences and exact-length walks using matrix exponentiation.
- Identify the structure (convexity, split monotonicity or quadrangle inequality) enabling each optimization.
- Implement the convex hull trick, divide-and-conquer optimization and Knuth–Yao.
- Optimally partition a sequence into k contiguous blocks in O(kn log n).
Before you start
Motivation: one loop, many answers
Take an acyclic graph with weighted edges and traverse it in topological order. At each node combine the values of its predecessors with the weight of the connecting edge, and retain something. If “combine” means add and “retain” means take the minimum, the loop computes the shortest path in a DAG. If combining means multiplying and retaining means adding, and every edge weighs 1, the same loop counts paths. If weights are transition probabilities and you retain the maximum, you obtain the most probable path: the Viterbi algorithm. If you sum instead of maximizing, you obtain the total probability of observations: the forward algorithm of a hidden Markov model.
These are not four similar algorithms. They are one algorithm instantiated in four algebraic structures, semirings, and the first half of this lesson makes that precise. The reward is twofold. First, one implementation serves everything, and changing the semiring gives variants for free: widest path, the smooth maximum used in structured losses, reachability. Second, the framework says exactly which property each step uses: distributivity. It also gives matrix exponentiation, computing a linear recurrence or walks of exact length in products.
The second half asks a different question. Many dynamic programs have states and a transition examining candidates, costing ; with layers, . With that is evaluations per layer. Splitting a 100-layer model into balanced pipeline stages is small, but segmenting a million-point time series, splitting a paragraph into optimal lines (the Knuth–Plass algorithm used by TeX), or grouping a million real values into optimal clusters is not. These techniques (monotone queue, convex hull trick, divide and conquer on the argmin, Knuth–Yao, SMAWK) reduce complexity by an order, to or per layer. None is merely a contest trick: each exploits a specific cost-function property, and applying it without checking that property gives silently incorrect results. You will see when and how to detect that.
Semirings
A semiring is what remains of a ring when subtraction is given up.
A monoid is exactly what is needed to aggregate a list of any length without worrying about parenthesization. What is missing compared with a ring is additive inverses: in general no exists with . This absence is consequential. In , does not allow recovering from and , which determines which tricks work.
| Semiring | Computes over paths | |||||
|---|---|---|---|---|---|---|
| Boolean | does any exist? | |||||
| Tropical | shortest | |||||
| Arctic | longest | |||||
| Counting, probability | or | number or total mass | ||||
| Viterbi | most probable | |||||
| Logarithmic | log of total mass | |||||
| Bottleneck | widest | |||||
| Languages | sets of strings | concatenation | all labels |
Checking the axioms is routine but worth doing once. In the tropical semiring, distributivity is : adding a constant does not change which of two values is smaller. The absorbing element is because . For bottlenecks, distributivity is , true because is monotone. Boolean, tropical, arctic, Viterbi and bottleneck semirings are selective; the language semiring is idempotent but not selective, while counting and logarithmic are not even idempotent.
Two relationships are useful to see now:
- Viterbi is a piece of the arctic semiring. Logarithm is an isomorphism onto the subsemiring of nonpositive arctic values: it preserves order, turns products into sums and maps and to and . Thus in practice Viterbi is implemented in with log probabilities.
- The logarithmic semiring is a smooth maximum. With temperature , define . Then , and as semiring tends to arctic . This is log-sum-exp as a smooth maximum, the bridge between “hard” inference (best path) and “soft” inference (all weighted paths).
Generic dynamic programming
Let be a directed acyclic graph, a source with no incoming edges, and weights in a semiring. The weight of a path is the ordered product , with for the empty path. Because the graph is acyclic, finitely many paths join any two nodes.
Proof
The only path from to is empty, because has no incoming edges and the graph is acyclic; its weight is . For , every path from to has a final edge ; removing it leaves a path from to . This is a bijection between and the disjoint union of . Since is associative and commutative, group the sum by final edge:
The second equality is right distributivity applied to a finite sum (by induction on its number of terms). If is empty, its term is by absorption and contributes nothing. What remains is .
∎That pattern, a topological order of subproblems plus a recurrence using only and , is what we call semiring dynamic programming. The dynamic programs of lesson 15, written on the subproblem DAG, fit it: edit distance is a shortest path in over the table grid, and CYK is the same idea over hypergraphs, with Boolean semiring for recognition, Viterbi for the best tree and sum-product for sentence probability (Goodman, 1999, called it semiring parsing).
The proof uses distributivity in one precise place: to take outside a sum with exponentially many terms. That is the source of efficiency and also its limit: if the quantity to aggregate does not distribute, the loop no longer computes what you think.
With initial weights, the same traversal yields at : a shortest path of length 7 (), a longest path of length 28 (), 10 paths, a most probable path with probability (), a smooth maximum of at temperature 1 and a widest path of capacity 6 (). Four optimization problems with four different winners, computed with the same 15 multiplications and 7 additions. In the probability semiring, : transition probabilities normalize each node’s outgoing weights, every random walk from ends at , and is the probability of passing through .
Thicknesses in sum mode are not decoration. If you also make the backward pass, with , then is the sum of weights of paths using edge , and divided by is the probability that a path sampled in proportion to its weight uses it. This is forward-backward. There is a deeper interpretation: in the logarithmic semiring that probability is exactly . The backward pass is reverse-mode differentiation of the forward pass, an observation Eisner (2016) summarized in a paper title: inside-outside and forward-backward “are just backpropagation”. In selective semirings, the derivative of the maximum is the indicator of the winning argument, and the backward pass degenerates to following optimal-path pointers.
Beyond DAGs: cycles and closure
With cycles, the number of paths is infinite and the defining sum must make sense. A semiring is closed if such infinite sums are well-defined, also distributes over them, and therefore every element has a star satisfying . In Boolean, . In tropical restricted to nonnegative weights, : going around a cycle never shortens a path. With negative weight, the infimum of is , not even in : the star does not exist, and precisely such a cycle is detected by Bellman–Ford. In counting, the star of 1 does not exist: a cycle produces infinitely many paths. In languages, the star is the Kleene star of regular expressions, and with it Floyd–Warshall becomes the algorithm transforming an automaton into a regular expression. You will prove this in the exercises. The general framework, including algorithms for these infinite sums on cyclic graphs, is Mohri’s (2002).
Viterbi and forward: the same trellis
A hidden Markov model with states , initial distribution , transitions and emissions defines a layered DAG, the trellis: one node per time and state, and edges weighted . The previous theorem immediately gives
In , is : the forward algorithm. In it is , the joint probability of the best state sequence and the observations: Viterbi. Each step is a vector–matrix product over the semiring, so the cost is instead of sequences.
The practical problem is numerical. If each observation has probability on the order of , 2000 observations have probability on the order of , and the smallest representable positive float64 is . Computed in , the result is exactly . The solution is logarithms, changing semiring: Viterbi moves to , which is exact, and forward to the logarithmic semiring, where is evaluated as with to avoid overflow (the log-sum-exp trick). Neural networks aligning sequences, such as the CTC loss for speech recognition, use exactly this dynamic program over the logarithmic semiring, automatically differentiated.
Matrix exponentiation
Weights of a graph with nodes fit in a matrix with , or if no edge exists. Matrix product is defined over any semiring by copying the usual matrix multiplication formula:
The identity has on its diagonal and elsewhere, and the product is associative: the usual proof uses only associativity of and , commutativity of and distributivity on both sides.
Proof
Induct on . For , the only walk with 0 edges is the empty walk from to , of weight , and is the identity. For the step, every walk from to with edges decomposes uniquely into a walk from to some with edges followed by edge . Grouping by and factoring out by distributivity, as in the preceding theorem, the sum is . If is not an edge, cancels the term.
∎Since multiplication is associative, is computed by fast exponentiation: and , with at most products costing . This matrix exponentiation for dynamic programming solves any recurrence whose step is “the same matrix–vector product” in instead of :
- Linear recurrences. becomes , giving . An order- recurrence uses the companion matrix , and is calculated with about 120 products of .
- Exact-length walks. In with the adjacency matrix, counts walks from to with edges. In it gives the shortest walk with exactly edges; with , with at most edges, and with all shortest distances in if there are no negative cycles.
- Dynamic programs with a fixed step. A recurrence such as is a product in by a constant matrix , and its value at comes from tropical exponentiation. This is the Bellman equation with fixed horizon and deterministic transitions.
The common structure does not mean fast multiplication algorithms work for all semirings. Strassen and successors compute combinations like and then subtract extra terms: they need a ring. In subtraction is unavailable, and for arbitrary real weights no algorithm is known for product, or all shortest distances, in time . The best known, Williams (2014), gains a subpolynomial factor, , and the conjecture that cannot be beaten underpins fine-grained complexity.
From scratch: a semiring in Python
A four-field class and a ten-line function suffice for all preceding examples. Comparison with networkx checks that shortest path, longest path and number of paths are correct.
import math
from dataclasses import dataclass
from typing import Callable
@dataclass(frozen=True)
class Semianillo:
nombre: str
suma: Callable # ⊕
prod: Callable # ⊗
cero: object # neutro de ⊕ y absorbente de ⊗
uno: object # neutro de ⊗
def logsumexp2(a, b):
if a == -math.inf: return b
if b == -math.inf: return a
m = max(a, b)
return m + math.log(math.exp(a - m) + math.exp(b - m))
MIN_PLUS = Semianillo("(min, +)", min, lambda a, b: a + b, math.inf, 0)
MAX_PLUS = Semianillo("(max, +)", max, lambda a, b: a + b, -math.inf, 0)
CONTEO = Semianillo("(+, ×)", lambda a, b: a + b, lambda a, b: a * b, 0, 1)
VITERBI = Semianillo("(max, ×)", max, lambda a, b: a * b, 0.0, 1.0)
LOG = Semianillo("(logsumexp, +)", logsumexp2, lambda a, b: a + b, -math.inf, 0.0)
ANCHO = Semianillo("(max, min)", max, min, -math.inf, math.inf)
BOOLEANO = Semianillo("(∨, ∧)", lambda a, b: a or b, lambda a, b: a and b, False, True)
def dp_dag(nodos, aristas, origen, S, valor):
"""V(v) = ⊕ sobre las aristas (u, v) de V(u) ⊗ valor(arista); nodos en orden topológico."""
V = {v: S.cero for v in nodos}
V[origen] = S.uno
entrantes = {v: [] for v in nodos}
for (u, v, w) in aristas:
entrantes[v].append((u, w))
for v in nodos:
for (u, w) in entrantes[v]:
V[v] = S.suma(V[v], S.prod(V[u], valor(u, v, w)))
return V
# el grafo de la figura
nodos = list("sabcdefgt")
aristas = [("s","a",5), ("s","b",2), ("s","d",6), ("a","c",9), ("a","d",7), ("b","d",9), ("b","e",4),
("c","f",5), ("c","t",5), ("d","f",8), ("d","g",9), ("e","g",7), ("e","t",1), ("f","t",8), ("g","t",4)]
salida = {u: sum(w for (a, _, w) in aristas if a == u) for u in nodos}
peso = lambda u, v, w: w
prob = lambda u, v, w: w / salida[u] # probabilidad de transición
uno = lambda u, v, w: 1
for S, valor in [(MIN_PLUS, peso), (MAX_PLUS, peso), (CONTEO, uno), (CONTEO, prob),
(VITERBI, prob), (LOG, peso), (ANCHO, peso), (BOOLEANO, lambda u, v, w: True)]:
print(f"{S.nombre:16s} V(t) = {dp_dag(nodos, aristas, 's', S, valor)['t']:.4g}")
import networkx as nx
G = nx.DiGraph()
G.add_weighted_edges_from(aristas)
print("\nnetworkx: más corto", nx.shortest_path_length(G, "s", "t", weight="weight"),
"| más largo", nx.dag_longest_path_length(G),
"| caminos", sum(1 for _ in nx.all_simple_paths(G, "s", "t")))Now generic matrix product and binary exponentiation. The same code computes with exact integers, counts walks and gives shortest paths with an exact number of edges. Notice the NumPy line: matrix_power with int64 overflows silently because exceeds .
import numpy as np
def matmul(S, A, B):
n, m, p = len(A), len(B), len(B[0])
C = [[S.cero] * p for _ in range(n)]
for i in range(n):
for k in range(m):
if A[i][k] == S.cero: # ⊗ por el cero da cero: se puede saltar
continue
for j in range(p):
C[i][j] = S.suma(C[i][j], S.prod(A[i][k], B[k][j]))
return C
def identidad(S, n):
return [[S.uno if i == j else S.cero for j in range(n)] for i in range(n)]
def matpow(S, A, k):
"""A^k en el semianillo S con O(log k) productos (exponenciación binaria)."""
R, P = identidad(S, len(A)), A
while k:
if k & 1:
R = matmul(S, R, P)
P = matmul(S, P, P)
k >>= 1
return R
F = [[1, 1], [1, 0]]
print("F_90 =", matpow(CONTEO, F, 90)[0][1])
print("F_100 =", matpow(CONTEO, F, 100)[0][1], "(enteros de Python, exacto)")
print("numpy int64:", np.linalg.matrix_power(np.array(F, dtype=np.int64), 100)[0, 1], "(desbordado sin aviso)")
# paseos en un grafo pequeño: el ciclo 0-1-2-3-0 con la cuerda 0-2
A = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
print("\npaseos de longitud 10 desde 0:", matpow(CONTEO, A, 10)[0])
# el mismo código en (min, +): camino más corto con exactamente k aristas
INF = math.inf
W = [[INF, 4, 1, INF], [INF, INF, INF, 1], [INF, 2, INF, 5], [3, INF, INF, INF]]
for k in [1, 2, 3, 4, 8]:
print(f"k = {k}: distancias desde 0 con exactamente k aristas:", matpow(MIN_PLUS, W, k)[0])The last table contains coming and going: with exactly 2 edges neither 0 nor 2 is reachable from 0; with 3, neither 1 nor 2; with 8, all are. The shortest 3-edge walk from 0 to 0 has length 8 ( costs , but costs ). Exact length is a real constraint, not the usual distance.
A hidden Markov model’s trellis is the same function with a different matrix. The cell compares Viterbi and forward in the log domain with enumeration of state sequences, then repeats the calculation with 2000 observations.
import itertools
from scipy.special import logsumexp
pi = np.array([0.6, 0.4]) # estados: 0 = soleado, 1 = lluvioso
Atr = np.array([[0.7, 0.3], [0.4, 0.6]]) # Atr[i, j] = P(estado j | estado i)
Bem = np.array([[0.6, 0.3, 0.1], [0.1, 0.4, 0.5]]) # emisiones: pasear, comprar, limpiar
obs = [0, 1, 2, 2, 1, 0, 0, 2, 1, 2]
def trellis(obs, suma, prod, cero, a, b, p0):
"""α_t(j) = (⊕_i α_{t-1}(i) ⊗ a[i, j]) ⊗ b[j, o_t]: un producto vector-matriz por paso."""
alfa = [prod(p0[j], b[j][obs[0]]) for j in range(len(p0))]
for o in obs[1:]:
nuevo = []
for j in range(len(p0)):
acc = cero
for i in range(len(p0)):
acc = suma(acc, prod(alfa[i], a[i][j]))
nuevo.append(prod(acc, b[j][o]))
alfa = nuevo
return alfa
lA, lB, lpi = np.log(Atr), np.log(Bem), np.log(pi)
viterbi = max(trellis(obs, max, lambda x, y: x + y, -math.inf, lA, lB, lpi))
forward = logsumexp(trellis(obs, logsumexp2, lambda x, y: x + y, -math.inf, lA, lB, lpi))
def puntuacion(z): # log P(z, obs) de una secuencia concreta
s = lpi[z[0]] + lB[z[0], obs[0]]
for t in range(1, len(obs)):
s += lA[z[t - 1], z[t]] + lB[z[t], obs[t]]
return s
todas = [puntuacion(z) for z in itertools.product([0, 1], repeat=len(obs))]
print("Viterbi en (max, +): ", viterbi, " fuerza bruta:", max(todas))
print("forward en (log-sum-exp, +):", forward, " fuerza bruta:", logsumexp(todas))
rng = np.random.default_rng(0)
largo = list(rng.integers(0, 3, size=2000))
directo = trellis(largo, lambda x, y: x + y, lambda x, y: x * y, 0.0, Atr, Bem, pi)
enlog = logsumexp(trellis(largo, logsumexp2, lambda x, y: x + y, -math.inf, lA, lB, lpi))
print("\n2000 observaciones en (+, ×):", sum(directo))
print("2000 observaciones en (log-sum-exp, +):", enlog, f"= 10^{enlog / math.log(10):.1f}")The probability of 2000 observations is : about 650 orders of magnitude below the smallest positive float64. In the probability semiring the result is exactly zero, without error or warning; in the logarithmic semiring it is perfectly representable.
From O(n²) to nearly linear: transition structure
The second half considers a common recurrence with “one dimension of states and one of candidates”:
where depends on already computed values (for example or ) and is transition cost. Computing each by examining all costs , totaling . The following techniques avoid examining every candidate, each relying on a distinct property:
| Transition property | Technique | Cost per layer |
|---|---|---|
| is a moving window and | monotone queue | |
| , lines in | convex hull trick | or |
| argmin is monotone in (e.g. is Monge) | divide and conquer | |
| interval recurrence with quadrangular and monotone | Knuth–Yao | total, down from |
| Monge transition matrix, previous values known | SMAWK |
At the end you will see that the last four rows are the same property viewed from different angles.
Monotone queue
The simplest case is a window. A frog jumps across stones ; landing on stone costs and each jump advances at most stones. The minimum cost to reach is
The direct loop costs . But between consecutive stones the window changes only at its ends: enters and leaves. A structure maintaining the minimum of a sliding window suffices.
Why is discarding indices from the back correct? If and , index leaves the window before and while present is never strictly better than . It can never again be the unique minimum, so retaining it adds nothing. What remains in the queue is always the list of the window’s “backward records”: indices that could still become minimum at a future moment. By construction their values increase, and the window minimum is first.
Total cost is by amortized analysis: each index enters once and leaves at most once, from front or back, so total queue operations are at most , even if one step removes many.
The monotone queue needs a total order: it only works with a selective such as or . For a window over any semigroup (a matrix product in or transition matrices), use the two-stack queue from amortized analysis: each stack stores partial aggregates and the operation needs only to be associative. Neither needs subtraction, exactly what a semiring does not allow: a window minimum cannot be obtained as the difference of two prefix minima, unlike sums.
The same idea speeds up bounded knapsack, where item can be taken up to times: separating capacities by their remainder modulo weight turns the transition into a (value) maximum over a window of positions, reducing cost from to .
from collections import deque
import time
def rana_directa(c, w):
dp = [c[0]]
for i in range(1, len(c)):
dp.append(c[i] + min(dp[max(0, i - w):i]))
return dp
def rana_cola(c, w):
dp, cola = [c[0]], deque([0]) # índices con dp estrictamente creciente
for i in range(1, len(c)):
while cola[0] < i - w: # caducan por delante
cola.popleft()
dp.append(c[i] + dp[cola[0]])
while cola and dp[cola[-1]] >= dp[i]: # dominados por detrás
cola.pop()
cola.append(i)
return dp
rng = np.random.default_rng(1)
c = rng.integers(1, 100, size=20000).tolist()
for w in [10, 100, 1000]:
t = time.perf_counter(); d1 = rana_directa(c, w); t1 = time.perf_counter() - t
t = time.perf_counter(); d2 = rana_cola(c, w); t2 = time.perf_counter() - t
print(f"w = {w:4d}: iguales = {d1 == d2}, directo {t1*1e3:6.1f} ms, cola {t2*1e3:5.1f} ms")Direct-version time grows with even though min on a list is written in C; queue time is the same for any .
Convex hull trick
Now cost depends on both and , but in a special way. Our example for the rest of the lesson partitions a sequence of positive numbers into contiguous blocks, minimizing the sum of squared block sums. This is the simplest way to request balanced blocks (squares penalize large ones), appearing in splitting model layers into pipeline stages, segmenting a series or splitting text into lines. With prefix sums , the layered recurrence is
Expand the square and separate what depends only on :
Each candidate is a line , and computing evaluates the minimum of a set of lines at . This minimum, as a function of , is the lines’ lower envelope: a concave piecewise-linear function. Traversed left to right, its pieces have decreasing slopes, because for very negative the largest slope wins, and for very positive the smallest does.
The name comes from duality between lines and points: line corresponds to point , and lower-envelope lines are vertices of those points’ lower convex hull. What makes the technique work is a local criterion for deciding whether a line is redundant.
Proof
Let be the x-coordinate where and intersect, and analogously and . Since , holds exactly for ; since , holds exactly for . Thus is strictly minimal on interval , empty if and only if . It remains to show . If , at we have (because to the right of , beats ), so has already lost to and . The converse is analogous: if , at we have , hence . Cross products follow by multiplying by positive denominators.
∎The algorithm is then a stack. Insert lines in decreasing slope order; before pushing a new , while the stack’s last two satisfy the criterion with , pop . Each line enters once and leaves at most once: total. Queries have three cases:
- Increasing queries. Intersections between consecutive envelope pieces increase, so if only increases, the optimal line only advances along the envelope: a pointer that never retreats answers all queries in amortized . In partitioning, increases because are positive.
- Arbitrary queries. Binary search over intersections: per query.
- Arbitrary slope order. A stack no longer suffices. Use a dynamic envelope in a balanced tree or, more simply, a Li Chao tree: a segment tree over the domain, each node storing the line winning at its interval midpoint. On insertion compare at the midpoint, keep the winner and send the loser down to the half where it can still win, which is unique because two lines intersect at most once. Insertion and query cost for a domain of size ; the idea works for any family of functions intersecting pairwise at most once.
Divide-and-conquer optimization
The convex hull trick needs cost linear in something involving . Many useful transitions are not: squared error of fitting a segment by a constant, number of inverted pairs within a block, maximum of two quantities. What they share is a weaker, more general property of where the best split lies.
Fix a layer and call a matrix with one row per state and one column per candidate (with where ). Let be the leftmost argmin of row . If for every , argmins form a staircase, enabling a divide-and-conquer scheme:
def resolver(lo, hi, opt_lo, opt_hi): # filas lo..hi, argmin dentro de [opt_lo, opt_hi]
if lo > hi:
return
mid = (lo + hi) // 2
dp[mid], opt = min((M(mid, j), j) for j in range(opt_lo, min(mid - 1, opt_hi) + 1))
resolver(lo, mid - 1, opt_lo, opt) # las filas de arriba no pasan de opt
resolver(mid + 1, hi, opt, opt_hi) # las de abajo no bajan de opt
This is divide-and-conquer optimization. Each call solves the middle row by linear search and splits the problem in two, with column ranges also split at .
Proof
Correctness follows by induction on recursion: if , monotonicity guarantees for and for , so restricting the range cannot lose the argmin. (Using leftmost argmin and over pairs also resolves ties correctly.) For cost, consider calls at the same depth in the recursion tree. Their row ranges are disjoint and column ranges consecutive, sharing only endpoints, so their lengths sum to at most . Since rows are halved, there are depths, each with at most nonempty calls. Total .
∎For layers, instead of . The essential question remains: when are argmins monotone?
The proof is one line once you see which two inequalities to add; you will do it in the guided exercise. Useful tools in practice for recognizing the quadrangle inequality:
- Adding single-variable functions does not change it: , and satisfy it with equality. Thus is harmless.
- Costs summing over pairs. If with , then satisfies it. Calling the set of pairs within : and , so .
- The squared sum is of this kind: , a prefix function plus a sum over pairs weighted . So is the number of inversions within a block, and, with a somewhat longer argument, squared error of fitting a constant to an ordered data segment, allowing exact one-dimensional k-means by dynamic programming.
The cost of the most expensive block, , is not of the form , but its argmins are also monotone; seeing why is a good exercise in this reasoning. Let be the leftmost argmin of row with finite minimum and let . If (a prefix too short for blocks), column equals in every row and is never the argmin of a finite row. Otherwise, since is nondecreasing where finite (with more numbers the best most-expensive block does not decrease), , so in row the maximum of is the second term: . Moving to row with , term increases by exactly and increases by at most . Therefore , and no can be the argmin of row .
The figure shows both sides of the condition. It is sufficient: the original matrix has no violations and the staircase is perfect. It is not necessary: small perturbations cause isolated violations while argmins can remain monotone. When the staircase breaks, divide and conquer returns a cost above optimum without any error signal: the algorithm assumes the property rather than checking it.
Now compare both methods in full on partitioning 800 numbers into 6 blocks, with both costs: squared sums and the most expensive block.
INF = math.inf
def prefijos(a):
S = [0]
for x in a:
S.append(S[-1] + x)
return S
def particion_directa(a, k, coste):
"""dp_capa[i] = min_{j<i} coste(dp_{capa-1}[j], S_i - S_j): O(k n^2) evaluaciones."""
n, S, ev = len(a), prefijos(a), 0
prev = [0] + [INF] * n # 0 bloques: solo el prefijo vacío
for _ in range(k):
cur = [INF] * (n + 1)
for i in range(1, n + 1):
mejor = INF
for j in range(i):
ev += 1
v = coste(prev[j], S[i] - S[j])
if v < mejor:
mejor = v
cur[i] = mejor
prev = cur
return prev[n], ev
def particion_dyv(a, k, coste):
"""Lo mismo, suponiendo opt(i) <= opt(i+1): O(k n log n) evaluaciones."""
n, S, ev = len(a), prefijos(a), 0
prev = [0] + [INF] * n
for _ in range(k):
cur = [INF] * (n + 1)
pila = [(1, n, 0, n - 1)] # (filas lo..hi, columnas olo..ohi), sin recursión
while pila:
lo, hi, olo, ohi = pila.pop()
if lo > hi:
continue
mid = (lo + hi) // 2
mejor, arg = INF, olo
for j in range(olo, min(mid - 1, ohi) + 1):
ev += 1
v = coste(prev[j], S[mid] - S[j])
if v < mejor:
mejor, arg = v, j
cur[mid] = mejor
pila.append((lo, mid - 1, olo, arg))
pila.append((mid + 1, hi, arg, ohi))
prev = cur
return prev[n], ev
cuadratico = lambda d, s: d + s * s # suma de cuadrados de los bloques
cuello = lambda d, s: d if d > s else s # el bloque más caro
rng = np.random.default_rng(0)
a = rng.integers(1, 100, size=800).tolist()
k = 6
for nombre, coste in [("suma de cuadrados", cuadratico), ("bloque más caro", cuello)]:
t = time.perf_counter(); r1, e1 = particion_directa(a, k, coste); t1 = time.perf_counter() - t
t = time.perf_counter(); r2, e2 = particion_dyv(a, k, coste); t2 = time.perf_counter() - t
print(f"{nombre:18s} directo {r1} ({e1:,} evaluaciones, {t1:.2f} s) | "
f"divide y vencerás {r2} ({e2:,} evaluaciones, {t2:.3f} s)")Both methods give the same optimum with 1,922,400 and about 46,200 evaluations: a factor of 42, growing like and on of order 3000. For quadratic cost the convex hull trick goes further, because slopes decrease and queries increase: each layer costs .
def particion_cht(a, k):
"""Suma de cuadrados con convex hull trick. Rectas y = m x + b con m = -2 S_j, b = dp[j] + S_j^2."""
n, S = len(a), prefijos(a)
prev = [0] + [INF] * n
def sobra(m1, b1, m2, b2, m3, b3): # el lema, con enteros: exacto
return (b3 - b1) * (m1 - m2) <= (b2 - b1) * (m1 - m3)
for _ in range(k):
cur = [INF] * (n + 1)
M, B, p = [], [], 0 # la envolvente y el puntero
for i in range(1, n + 1):
j = i - 1 # el corte j = i - 1 ya es un candidato
if prev[j] < INF:
m, b = -2 * S[j], prev[j] + S[j] * S[j]
while len(M) >= 2 and sobra(M[-2], B[-2], M[-1], B[-1], m, b):
M.pop(); B.pop()
M.append(m); B.append(b)
p = min(p, len(M) - 1)
if M:
x = S[i] # consultas crecientes
while p + 1 < len(M) and M[p + 1] * x + B[p + 1] <= M[p] * x + B[p]:
p += 1
cur[i] = M[p] * x + B[p] + x * x
prev = cur
return prev[n]
t = time.perf_counter(); r3 = particion_cht(a, k); t3 = time.perf_counter() - t
print(f"convex hull trick: {r3}, {t3 * 1e3:.1f} ms")
# comprobación aleatoria contra la versión directa, en casos pequeños
import random
random.seed(3)
for _ in range(300):
n = random.randint(1, 25); kk = random.randint(1, n)
aa = [random.randint(1, 30) for _ in range(n)]
assert particion_cht(aa, kk) == particion_directa(aa, kk, cuadratico)[0]
assert particion_dyv(aa, kk, cuello)[0] == particion_directa(aa, kk, cuello)[0]
print("300 casos aleatorios: los tres métodos coinciden")
b = rng.integers(1, 10**6, size=20000).tolist()
t = time.perf_counter(); particion_cht(b, 16); t4 = time.perf_counter() - t
print(f"n = 20000, k = 16 con convex hull trick: {t4:.2f} s")Random checking against the direct version on small cases is the standard defense against this lesson’s most dangerous error: applying an optimization whose assumption fails. It takes ten lines and detects both incorrect reasoning about a property and index errors.
Knuth-Yao
Interval dynamic programs from the preceding lesson, such as the optimal binary search tree, have states and splits per state: . Knuth (1971) observed the optimal search-tree root is monotone and reduced cost to ; Yao (1980) identified the abstract property justifying it. The general form, for , is
and call the largest attaining the minimum.
Proof
(1) Induct on . If or , the inequality is equality. Write .
Case . We must show . Let . If , is a valid split for and, using , . By the induction hypothesis (with and ), , leaving . If , split is valid for and, with , ; by induction (), , again leaving .
Case . Let and . If , is valid for and for : . The quadrangle inequality for and induction applied to give . If , use for and for , and induction on closes similarly.
(2) Let . By (1) with : . Adding to both sides,
Take . If , inequality is trivial. Otherwise, every valid for with satisfies , and the preceding inequality gives : no split left of is strictly better for , so the largest optimal split of is at least . The other half, , is symmetric.
Cost. For fixed length , work is . The sum telescopes: terms cancel in pairs except the first and last, between 0 and , leaving evaluations per length. With lengths, .
∎This Knuth–Yao speedup applies directly to optimal search trees, where is the sum of interval frequencies (additive, hence quadrangular with equality, and monotone because frequencies are nonnegative), and to the optimal alphabetic tree: a prefix code respecting leaf order, equivalently the order for merging adjacent piles while paying the result’s size each time. The cell solves 300 leaves both ways. To use bounds , fill the table by interval length, as in every interval dynamic program.
def intervalos(n, coste, knuth=False):
"""c(i, j) = min_{i<r<j} c(i, r) + c(r, j) + coste(i, r, j) sobre [i, j) semiabierto, c(i, i+1) = 0.
Con knuth=True, r solo recorre [opt(i, j-1), opt(i+1, j)]. Aquí opt es el menor corte óptimo:
el teorema usa el mayor, pero el mismo argumento con desigualdades estrictas vale para el menor."""
c = [[0] * (n + 1) for _ in range(n + 1)]
opt = [[0] * (n + 1) for _ in range(n + 1)]
ev = 0
for L in range(2, n + 1): # por longitud creciente
for i in range(n - L + 1):
j = i + L
lo, hi = (opt[i][j - 1], opt[i + 1][j]) if knuth and L > 2 else (i + 1, j - 1)
mejor, arg = INF, lo
for r in range(lo, hi + 1):
ev += 1
v = c[i][r] + c[r][j] + coste(i, r, j)
if v < mejor:
mejor, arg = v, r
c[i][j], opt[i][j] = mejor, arg
return c[0][n], ev
# árbol alfabético óptimo: hojas con frecuencias f, coste = suma de f por profundidad
rng = np.random.default_rng(2)
f = rng.integers(1, 1000, size=300).tolist()
Sf = prefijos(f)
alfabetico = lambda i, r, j: Sf[j] - Sf[i] # w(i, j): no depende del corte r
t = time.perf_counter(); c1, e1 = intervalos(len(f), alfabetico); t1 = time.perf_counter() - t
t = time.perf_counter(); c2, e2 = intervalos(len(f), alfabetico, knuth=True); t2 = time.perf_counter() - t
print(f"árbol alfabético, n = {len(f)}: directo {c1} ({e1:,} evaluaciones, {t1:.2f} s), "
f"Knuth {c2} ({e2:,} evaluaciones, {t2:.3f} s)")
# la cadena de matrices NO cumple las hipótesis: Knuth puede fallar sin avisar
p = [1, 1, 2, 3, 1]
cadena = lambda i, r, j: p[i] * p[r] * p[j]
print("cadena", p, ": directo", intervalos(4, cadena)[0], "| con Knuth", intervalos(4, cadena, knuth=True)[0])
fallos = 0
for _ in range(1000):
p = rng.integers(1, 30, size=7).tolist()
cadena = lambda i, r, j: p[i] * p[r] * p[j]
fallos += intervalos(6, cadena)[0] != intervalos(6, cadena, knuth=True)[0]
print(f"cadenas aleatorias de 6 matrices en las que Knuth se equivoca: {fallos} de 1000")Monge matrices and SMAWK
The conditions of the preceding three sections express the same property.
It suffices to check the Monge condition in adjacent submatrices, : summing those inequalities over a rectangle cancels interior terms, leaving the inequality for the whole rectangle. That is what the crosses in the figure count. Monge implies total monotonicity: if and , adding gives , contradicting the condition. Now the pieces fit:
- The matrix of transition with quadrangular is Monge (rows are and columns ). Divide-and-conquer argmin monotonicity is total monotonicity.
- The convex hull trick’s line matrix, with decreasing and increasing , is Monge: .
- The Knuth–Yao quadrangle inequality is the Monge condition for , viewed as a matrix indexed by interval endpoints (the other assumption, monotonicity under inclusion, is separate).
The SMAWK algorithm (initials of Aggarwal, Klawe, Moran, Shor and Wilber, 1987) finds minima of all rows of a totally monotone matrix with evaluations, without storing the matrix. It has two phases. Reduce removes columns using a stack where the column at position can only be minimum for rows onward: if in row at the top the new column wins strictly, total monotonicity says it also wins in every lower row, and in upper rows the previous stack column was already at least as good and farther left, so pop; at most useful columns remain after comparisons. Then recurse on every other row (odd indices, counting from 0) and interpolate the rest: by monotonicity, each minimum lies between its two neighbors’ minima, and traversing these gaps costs total. Cost satisfies , giving . This theory of Monge matrices and SMAWK reduces layered partitioning to with any quadrangular cost, not only linear ones.
def smawk(filas, cols, M, cuenta):
"""argmin más a la izquierda de cada fila de una matriz totalmente monótona: O(len(filas) + len(cols))."""
if not filas:
return {}
def m(i, j):
cuenta[0] += 1
return M(i, j)
# REDUCE: deja como mucho len(filas) columnas candidatas
pila = []
for c in cols:
while pila and m(filas[len(pila) - 1], pila[-1]) > m(filas[len(pila) - 1], c):
pila.pop()
if len(pila) < len(filas):
pila.append(c)
# recursión sobre las filas impares
res = smawk(filas[1::2], pila, M, cuenta)
# INTERPOLA: cada fila par busca entre los argmin de sus vecinas
k = 0
for r in range(0, len(filas), 2):
fin = res[filas[r + 1]] if r + 1 < len(filas) else pila[-1]
mejor, arg = m(filas[r], pila[k]), pila[k]
while pila[k] != fin:
k += 1
v = m(filas[r], pila[k])
if v < mejor:
mejor, arg = v, pila[k]
res[filas[r]] = arg
return res
def monge_aleatoria(n, m, rng):
"""(x_i - y_j)^2 con x, y ordenados es de Monge; sumarle un término por columna lo conserva."""
x, y = np.sort(rng.random(n)), np.sort(rng.random(m))
return (x[:, None] - y[None, :]) ** 2 + rng.random(m)[None, :] * 0.3
rng = np.random.default_rng(5)
for n in [100, 1000, 4000]:
M = monge_aleatoria(n, n, rng)
cuenta = [0]
res = smawk(list(range(n)), list(range(n)), lambda i, j: M[i, j], cuenta)
ok = all(res[i] == int(np.argmin(M[i])) for i in range(n))
print(f"n = {n:5d}: correcto = {ok}, evaluaciones = {cuenta[0]:,} "
f"({cuenta[0] / n:.1f} por fila; fuerza bruta: {n * n:,})")Evaluations per row remain around a small constant while grows by a factor of 40. In practice divide and conquer is simpler and its factor barely noticeable, so SMAWK is reserved for when matters or minima of a large implicit matrix are needed.
A scope warning: SMAWK and divide and conquer require the layer’s matrix to be defined in advance, meaning column values must not depend on rows being computed. In a single-layer recurrence, , column only exists once row has been computed. For that “online” case with quadrangular there are algorithms maintaining a candidate queue and using binary search to find where each begins winning, and even (Larmore and Schieber, 1991).
The Aliens trick in one paragraph
If optimal cost with exactly blocks, , is convex in , the dimension can be removed entirely using Lagrangian relaxation: for price per block solve , a single-layer dynamic program, and use binary search on the answer for the at which the optimal solution uses blocks; then . Convexity guarantees this exists (it is a slope of ), reducing cost from to . The name comes from the “Aliens” problem at the 2016 International Olympiad in Informatics, which popularized it.
The library version
There is no standard “semiring dynamic programming” library, but there are pieces for each case:
| Need | Tool |
|---|---|
| graph paths | networkx, scipy.sparse.csgraph.shortest_path and floyd_warshall |
| stable log-sum-exp | scipy.special.logsumexp, np.logaddexp, torch.logsumexp |
| matrix product | NumPy broadcasting: (A[:, :, None] + B[None, :, :]).min(axis=1) |
| hidden Markov models and CRFs | vectorized forward, Viterbi and forward-backward in PyTorch |
| differentiable structured dynamic programming | libraries such as Torch-Struct (Rush, 2020), which parameterize the semiring |
from scipy.sparse.csgraph import floyd_warshall
def minplus(A, B):
"""Producto (min, +) vectorizado: C[i, j] = min_k A[i, k] + B[k, j]."""
return (A[:, :, None] + B[None, :, :]).min(axis=1)
rng = np.random.default_rng(4)
n = 120
W = np.where(rng.random((n, n)) < 0.05, rng.integers(1, 20, size=(n, n)).astype(float), np.inf)
np.fill_diagonal(W, 0) # con 0 en la diagonal, A^k = caminos de hasta k aristas
D, pasos = W.copy(), 0
while (1 << pasos) < n - 1:
D = minplus(D, D)
pasos += 1
FW = floyd_warshall(W, directed=True) # inf significa «no hay arista»
print(f"{pasos} cuadrados (min, +) frente a Floyd-Warshall de SciPy: iguales = {np.array_equal(D, FW)}")
logp = rng.normal(-800, 5, size=5000) # log-probabilidades muy pequeñas
with np.errstate(divide="ignore"):
ingenuo = np.log(np.exp(logp).sum())
print("logsumexp:", logsumexp(logp), "| np.logaddexp.reduce:", np.logaddexp.reduce(logp), "| ingenuo:", ingenuo)The vectorized product materializes a tensor , so memory is : with it is 14 MB, with it would be 8 GB. For large matrices split into row blocks. The naive log-sum-exp version returns : each is 0 in float64.
In PyTorch, a hidden Markov model or linear CRF’s forward recursion is the same loop over time with torch.logsumexp(alpha[:, :, None] + log_A, dim=1) + log_B[:, obs[t]], and loss.backward() performs forward-backward without writing it. Viterbi is the same line with max instead of logsumexp, plus pointers for path reconstruction.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 3. What do you know about row comparing columns and ?
Step 1 of 4. What do paths not using as an intermediate contribute?
minimos_rectas(rectas, consultas). Lines are integer pairs (m, b) with strictly decreasing slopes; queries are integers in nondecreasing order. Return the list of for each query in time: build the envelope using a stack and the lemma's criterion (cross products without division), then traverse it with a pointer that only advances.def minimos_rectas(rectas, consultas):
"""rectas: lista de (m, b) enteros con m estrictamente decreciente.
consultas: lista de x enteros en orden no decreciente.
Devuelve [min_j m_j * x + b_j para cada x], en O(len(rectas) + len(consultas))."""
# tu código: envolvente inferior con una pila, después un puntero que solo avanza
return []potencia_minplus(W, k): given weight matrix W of a directed graph (math.inf where no edge exists; weights may be negative), return matrix D with D[i][j] equal to the minimum length of a walk from i to j with exactly k edges (math.inf if none exists). Use product, the semiring identity and binary exponentiation so k may be .import math
def potencia_minplus(W, k):
"""W[i][j]: peso de la arista i -> j (math.inf si no existe). Devuelve D con
D[i][j] = longitud mínima de un paseo de i a j con exactamente k aristas, con O(log k) productos."""
n = len(W)
# tu código: producto (min, +), identidad del semianillo y exponenciación binaria
return WSummary
- A semiring is a ring without subtraction. Dynamic programming over a DAG computes using products: gives shortest paths, counts or sums probabilities, is Viterbi, and logarithmic is stable forward, a smooth maximum tending to as .
- The backward pass in a sum semiring gives edge marginals (forward-backward), which are derivatives of the forward pass.
- Matrix product is associative over any semiring: sums walks with exactly edges and is computed with products. Strassen does not work without subtraction.
- Monotone queue for window minima, amortized . Convex hull trick when cost is : stack plus pointer for monotone slopes and queries, otherwise binary search or Li Chao.
- Divide and conquer between layers when argmins are monotone, guaranteed by the quadrangle inequality; Knuth–Yao on intervals with quadrangular and monotone , from to ; SMAWK finds minima of all rows of a Monge matrix in .
- Before trusting an optimized version, compare it against the direct one on small random cases.