Module contents
Lesson 17 of 33Advanced 115 min

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 vv 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 kk in O(log⁡k)\bigO(\log k) products.

The second half asks a different question. Many dynamic programs have nn states and a transition examining O(n)\bigO(n) candidates, costing O(n2)\bigO(n^2); with kk layers, O(kn2)\bigO(kn^2). With n=105n = 10^5 that is 101010^{10} 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 kk 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 O(n)\bigO(n) or O(nlog⁡n)\bigO(n \log n) 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 bb exists with a⊕b=0ˉa \oplus b = \bar{0}. This absence is consequential. In (min⁡,+)(\min, +), min⁡(a,b)=c\min(a, b) = c does not allow recovering aa from bb and cc, which determines which tricks work.

SemiringKK⊕\oplus⊗\otimes0ˉ\bar{0}1ˉ\bar{1}Computes over paths
Boolean{0,1}\{0, 1\}∨\lor∧\land0011does any exist?
TropicalR∪{+∞}\R \cup \{+\infty\}min⁡\min+++∞+\infty00shortest
ArcticR∪{−∞}\R \cup \{-\infty\}max⁡\max++−∞-\infty00longest
Counting, probabilityR≥0\R_{\ge 0} or N\N++×\times0011number or total mass
Viterbi[0,1][0, 1]max⁡\max×\times0011most probable
LogarithmicR∪{−∞}\R \cup \{-\infty\}log⁡(ea+eb)\log(e^a + e^b)++−∞-\infty00log of total mass
BottleneckR∪{±∞}\R \cup \{\pm\infty\}max⁡\maxmin⁡\min−∞-\infty+∞+\inftywidest
Languagessets of strings∪\cupconcatenation∅\varnothing{ε}\{\varepsilon\}all labels

Checking the axioms is routine but worth doing once. In the tropical semiring, distributivity is a+min⁡(b,c)=min⁡(a+b,a+c)a + \min(b, c) = \min(a + b, a + c): adding a constant does not change which of two values is smaller. The absorbing element is +∞+\infty because +∞+a=+∞+\infty + a = +\infty. For bottlenecks, distributivity is min⁡(a,max⁡(b,c))=max⁡(min⁡(a,b),min⁡(a,c))\min(a, \max(b, c)) = \max(\min(a, b), \min(a, c)), true because min⁡(a,⋅)\min(a, \cdot) 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 log⁡:([0,1],max⁡,×)→([−∞,0],max⁡,+)\log : ([0, 1], \max, \times) \to ([-\infty, 0], \max, +) is an isomorphism onto the subsemiring of nonpositive arctic values: it preserves order, turns products into sums and maps 00 and 11 to −∞-\infty and 00. Thus in practice Viterbi is implemented in (max⁡,+)(\max, +) with log probabilities.
  • The logarithmic semiring is a smooth maximum. With temperature T>0T > 0, define a⊕Tb=Tlog⁡(ea/T+eb/T)a \oplus_T b = T \log(e^{a/T} + e^{b/T}). Then max⁡(a,b)≤a⊕Tb≤max⁡(a,b)+Tlog⁡2\max(a, b) \le a \oplus_T b \le \max(a, b) + T \log 2, and as T→0T \to 0 semiring (⊕T,+)(\oplus_T, +) tends to arctic (max⁡,+)(\max, +). 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 G=(V,E)G = (V, E) be a directed acyclic graph, s∈Vs \in V a source with no incoming edges, and w:E→Kw : E \to K weights in a semiring. The weight of a path π=(e1,…,em)\pi = (e_1, \dots, e_m) is the ordered product w(π)=w(e1)⊗⋯⊗w(em)w(\pi) = w(e_1) \otimes \cdots \otimes w(e_m), with w(π)=1ˉw(\pi) = \bar{1} for the empty path. Because the graph is acyclic, finitely many paths join any two nodes.

Proof

The only path from ss to ss is empty, because ss has no incoming edges and the graph is acyclic; its weight is 1ˉ\bar{1}. For v≠sv \neq s, every path from ss to vv has a final edge (u,v)(u, v); removing it leaves a path from ss to uu. This is a bijection between Π(s,v)\Pi(s, v) and the disjoint union of Π(s,u)×{(u,v)}\Pi(s, u) \times \{(u, v)\}. Since ⊕\oplus is associative and commutative, group the sum by final edge:

V(v)=⨁(u,v)∈E  ⨁ρ∈Π(s,u)(w(ρ)⊗w(u,v))=⨁(u,v)∈E(⨁ρ∈Π(s,u)w(ρ))⊗w(u,v).V(v) = \bigoplus_{(u, v) \in E} \; \bigoplus_{\rho \in \Pi(s, u)} \big(w(\rho) \otimes w(u, v)\big) = \bigoplus_{(u, v) \in E} \Big(\bigoplus_{\rho \in \Pi(s, u)} w(\rho)\Big) \otimes w(u, v).

The second equality is right distributivity applied to a finite sum (by induction on its number of terms). If Π(s,u)\Pi(s, u) is empty, its term is 0ˉ⊗w(u,v)=0ˉ\bar{0} \otimes w(u, v) = \bar{0} by absorption and contributes nothing. What remains is ⨁(u,v)V(u)⊗w(u,v)\bigoplus_{(u,v)} V(u) \otimes w(u, v).

∎

That pattern, a topological order of subproblems plus a recurrence using only ⊕\oplus and ⊗\otimes, 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 (min⁡,+)(\min, +) 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 w(u,v)w(u, v) 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.

InteractiveChange the semiring
5269794558971840s5a2b14c6d6e14f13g7t
Recurrence at tt, in semiring (min⁡, +)(\min,\, +):
V(t)=V(c)⊗wct⊕V(e)⊗wet⊕V(f)⊗wft⊕V(g)⊗wgt=min⁡(14+5,  6+1,  14+8,  13+4)=7\begin{aligned} V(t) &= V(c) \otimes w_{ct} \oplus V(e) \otimes w_{et} \oplus V(f) \otimes w_{ft} \oplus V(g) \otimes w_{gt} \\ &= \min(14 + 5,\; 6 + 1,\; 14 + 8,\; 13 + 4) = 7 \end{aligned}
The same traversal in all eight semirings: value at tt
  • winning path
  • edges entering current-step node
  • removed edge
Topological order
complete
Selected edge
None: click an edge in the graph.
Value at tt7
Meaning: shortest path length. Edges: each edge is its length ww.
Operations ⊗\otimes / ⊕\oplus15 / 7
⊕\oplus is selective: one edge wins at each node, and a single path gives the result, highlighted from ss to tt.
A DAG of 9 nodes and 15 edges traversed in topological order. Each node contains its value V(v)V(v); edge labels are weights converted to the selected semiring. Change the semiring with the selector or cards below: traversal and operation count do not change, only their meaning. In selective semirings the winning path is highlighted; in sum semirings each edge's thickness is the fraction of paths using it. Click a node to see its recurrence, or an edge to change its weight or remove it. In the logarithmic semiring lower temperature to 0.05: which card does the value approach and what happens to thicknesses?

With initial weights, the same traversal yields at tt: a shortest path of length 7 (s→b→e→ts \to b \to e \to t), a longest path of length 28 (s→a→d→f→ts \to a \to d \to f \to t), 10 paths, a most probable path with probability 0.2440.244 (s→d→g→ts \to d \to g \to t), a smooth maximum of 28.5928.59 at temperature 1 and a widest path of capacity 6 (s→d→f→ts \to d \to f \to t). Four optimization problems with four different winners, computed with the same 15 multiplications and 7 additions. In the probability semiring, V(t)=1V(t) = 1: transition probabilities normalize each node’s outgoing weights, every random walk from ss ends at tt, and V(v)V(v) is the probability of passing through vv.

Thicknesses in sum mode are not decoration. If you also make the backward pass, B(u)=⨁(u,v)w(u,v)⊗B(v)B(u) = \bigoplus_{(u, v)} w(u, v) \otimes B(v) with B(t)=1ˉB(t) = \bar{1}, then V(u)⊗w(u,v)⊗B(v)V(u) \otimes w(u, v) \otimes B(v) is the sum of weights of paths using edge (u,v)(u, v), and divided by V(t)V(t) 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 ∂V(t)/∂w(u,v)\partial V(t) / \partial w(u, v). 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, ⊗\otimes also distributes over them, and therefore every element has a star a∗=1ˉ⊕a⊕a2⊕⋯a^* = \bar{1} \oplus a \oplus a^2 \oplus \cdots satisfying a∗=1ˉ⊕a⊗a∗=1ˉ⊕a∗⊗aa^* = \bar{1} \oplus a \otimes a^* = \bar{1} \oplus a^* \otimes a. In Boolean, a∗=1a^* = 1. In tropical restricted to nonnegative weights, a∗=min⁡(0,a,2a,… )=0a^* = \min(0, a, 2a, \dots) = 0: going around a cycle never shortens a path. With negative weight, the infimum of 0,a,2a,…0, a, 2a, \dots is −∞-\infty, not even in KK: 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 1,…,S1, \dots, S, initial distribution π\vb{\pi}, transitions aij=P(zt+1=j∣zt=i)a_{ij} = \Pr(z_{t+1} = j \given z_t = i) and emissions bj(o)=P(o∣z=j)b_j(o) = \Pr(o \given z = j) defines a layered DAG, the trellis: one node (t,j)(t, j) per time and state, and edges (t−1,i)→(t,j)(t - 1, i) \to (t, j) weighted aij bj(ot)a_{ij}\,b_j(o_t). The previous theorem immediately gives

αt(j)=(⨁iαt−1(i)⊗aij)⊗bj(ot),α1(j)=πj⊗bj(o1).\alpha_t(j) = \Big(\bigoplus_{i} \alpha_{t-1}(i) \otimes a_{ij}\Big) \otimes b_j(o_t), \qquad \alpha_1(j) = \pi_j \otimes b_j(o_1).

In (+,×)(+, \times), ⨁jαT(j)\bigoplus_j \alpha_T(j) is P(o1,…,oT)\Pr(o_1, \dots, o_T): the forward algorithm. In (max⁡,×)(\max, \times) it is max⁡zP(z1,…,zT,o1,…,oT)\max_{z} \Pr(z_1, \dots, z_T, o_1, \dots, o_T), 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 O(TS2)\bigO(TS^2) instead of STS^T sequences.

The practical problem is numerical. If each observation has probability on the order of 0.30.3, 2000 observations have probability on the order of 10−100010^{-1000}, and the smallest representable positive float64 is 4.9×10−3244.9 \times 10^{-324}. Computed in (+,×)(+, \times), the result is exactly 0.00.0. The solution is logarithms, changing semiring: Viterbi moves to (max⁡,+)(\max, +), which is exact, and forward to the logarithmic semiring, where log⁡(ea+eb)\log(e^a + e^b) is evaluated as m+log⁡(ea−m+eb−m)m + \log(e^{a - m} + e^{b - m}) with m=max⁡(a,b)m = \max(a, b) 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 1,…,n1, \dots, n fit in a matrix A\mat{A} with Aij=w(i,j)A_{ij} = w(i, j), or 0ˉ\bar{0} if no edge exists. Matrix product is defined over any semiring by copying the usual matrix multiplication formula:

(A⊗B)ij=⨁l=1nAil⊗Blj.(\mat{A} \otimes \mat{B})_{ij} = \bigoplus_{l=1}^{n} A_{il} \otimes B_{lj}.

The identity has 1ˉ\bar{1} on its diagonal and 0ˉ\bar{0} elsewhere, and the product is associative: the usual proof uses only associativity of ⊕\oplus and ⊗\otimes, commutativity of ⊕\oplus and distributivity on both sides.

Proof

Induct on kk. For k=0k = 0, the only walk with 0 edges is the empty walk from ii to ii, of weight 1ˉ\bar{1}, and A0\mat{A}^0 is the identity. For the step, every walk from ii to jj with k+1k + 1 edges decomposes uniquely into a walk from ii to some ll with kk edges followed by edge (l,j)(l, j). Grouping by ll and factoring out AljA_{lj} by distributivity, as in the preceding theorem, the sum is ⨁l(Ak)il⊗Alj=(Ak+1)ij\bigoplus_l (\mat{A}^k)_{il} \otimes A_{lj} = (\mat{A}^{k+1})_{ij}. If (l,j)(l, j) is not an edge, Alj=0ˉA_{lj} = \bar{0} cancels the term.

∎

Since multiplication is associative, Ak\mat{A}^k is computed by fast exponentiation: A2m=(Am)2\mat{A}^{2m} = (\mat{A}^m)^2 and A2m+1=A A2m\mat{A}^{2m+1} = \mat{A}\,\mat{A}^{2m}, with at most 2⌊log⁡2k⌋2\lfloor\log_2 k\rfloor products costing O(n3)\bigO(n^3). This matrix exponentiation for dynamic programming solves any recurrence whose step is “the same matrix–vector product” in O(n3log⁡k)\bigO(n^3 \log k) instead of O(n2k)\bigO(n^2 k):

  • Linear recurrences. Fm+1=Fm+Fm−1F_{m+1} = F_m + F_{m-1} becomes (Fm+1,Fm)⊤=[1110](Fm,Fm−1)⊤(F_{m+1}, F_m)\T = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}(F_m, F_{m-1})\T, giving [1110]m=[Fm+1FmFmFm−1]\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^m = \begin{bmatrix} F_{m+1} & F_m \\ F_m & F_{m-1} \end{bmatrix}. An order-dd recurrence uses the companion matrix d×dd \times d, and F1018 mod pF_{10^{18}} \bmod p is calculated with about 120 products of 2×22 \times 2.
  • Exact-length walks. In (+,×)(+, \times) with the adjacency matrix, (Ak)ij(\mat{A}^k)_{ij} counts walks from ii to jj with kk edges. In (min⁡,+)(\min, +) it gives the shortest walk with exactly kk edges; with (I⊕A)k(\mat{I} \oplus \mat{A})^k, with at most kk edges, and with k=n−1k = n - 1 all shortest distances in O(n3log⁡n)\bigO(n^3 \log n) if there are no negative cycles.
  • Dynamic programs with a fixed step. A recurrence such as f(m)=max⁡(f(m−1)+a,f(m−2)+b)f(m) = \max(f(m-1) + a, f(m-2) + b) is a product in (max⁡,+)(\max, +) by a constant matrix 2×22 \times 2, and its value at m=1018m = 10^{18} 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 (a+b)(c+d)−…(a + b)(c + d) - \dots and then subtract extra terms: they need a ring. In (min⁡,+)(\min, +) subtraction is unavailable, and for arbitrary real weights no algorithm is known for (min⁡,+)(\min, +) product, or all shortest distances, in time O(n3−ε)\bigO(n^{3 - \eps}). The best known, Williams (2014), gains a subpolynomial factor, n3/2Ω(log⁡n)n^3 / 2^{\Omega(\sqrt{\log n})}, and the conjecture that n3−o(1)n^{3 - o(1)} 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.

[ ]Generic dynamic programming on a DAGBrowser
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 F100F_{100} 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 F100≈3.5×1020F_{100} \approx 3.5 \times 10^{20} exceeds 263≈9.2×10182^{63} \approx 9.2 \times 10^{18}.

[ ]Matrices over a semiring and fast exponentiationBrowser
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 +∞+\infty 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 (0→2→3→00 \to 2 \to 3 \to 0 costs 1+5+3=91 + 5 + 3 = 9, but 0→1→3→00 \to 1 \to 3 \to 0 costs 4+1+3=84 + 1 + 3 = 8). 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 2102^{10} state sequences, then repeats the calculation with 2000 observations.

[ ]Viterbi and forward in the same trellisBrowser
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 10−971.610^{-971.6}: 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”:

dp[i]=min⁡j∈J(i)(f(j)+C(j,i)),dp[i] = \min_{j \in J(i)} \big( f(j) + C(j, i) \big),

where f(j)f(j) depends on already computed values (for example f(j)=dp[j]f(j) = dp[j] or f(j)=dpcapa anterior[j]f(j) = dp_{\text{capa anterior}}[j]) and C(j,i)C(j, i) is transition cost. Computing each dp[i]dp[i] by examining all jj costs O(n)\bigO(n), totaling O(n2)\bigO(n^2). The following techniques avoid examining every candidate, each relying on a distinct property:

Transition propertyTechniqueCost per layer
J(i)J(i) is a moving window and C(j,i)=c(i)C(j, i) = c(i)monotone queueO(n)\bigO(n)
C(j,i)=ajxi+bjC(j, i) = a_j x_i + b_j, lines in xix_iconvex hull trickO(n)\bigO(n) or O(nlog⁡n)\bigO(n \log n)
argmin is monotone in ii (e.g. CC is Monge)divide and conquerO(nlog⁡n)\bigO(n \log n)
interval recurrence with quadrangular and monotone wwKnuth–YaoO(n2)\bigO(n^2) total, down from O(n3)\bigO(n^3)
Monge transition matrix, previous values knownSMAWKO(n)\bigO(n)

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 0,1,…,n−10, 1, \dots, n - 1; landing on stone ii costs cic_i and each jump advances at most ww stones. The minimum cost to reach ii is

dp[i]=ci+min⁡i−w≤j<idp[j].dp[i] = c_i + \min_{i - w \le j < i} dp[j].

The direct loop costs O(nw)\bigO(nw). But between consecutive stones the window changes only at its ends: j=i−1j = i - 1 enters and j=i−w−1j = i - w - 1 leaves. A structure maintaining the minimum of a sliding window suffices.

Why is discarding indices from the back correct? If j<ij < i and dp[j]≥dp[i]dp[j] \ge dp[i], index jj leaves the window before ii and while present is never strictly better than ii. 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 O(n)\bigO(n) by amortized analysis: each index enters once and leaves at most once, from front or back, so total queue operations are at most 2n2n, even if one step removes many.

InteractiveThe monotone queue in action
window7078112531475565728395102111127135148158163177
Below each bar: stone index and cost cic_i.
  • queue head: minimum in window
  • rest of queue (increasing values)
  • current step dp
  • leaves queue this step
Stone being calculated
i = 1
4
Transitiondp[1] = 1 + dp[0] = 8
Queue (index: dp), head to tail:0: 71: 8
Cumulative removals / insertions0 / 2
Candidates examined by direct loop1
Bars are already computed dp[j]dp[j] values and the dotted band is the transition window for stone ii. Only colored bars remain in the queue: blue is the head, giving the minimum, and aquamarine the rest, with increasing values. Step forward and observe what leaves at the front (expires) and the back (dominated by the new stone). Compare removal and insertion counters for different ranges ww: removals never exceed insertions.

The monotone queue needs a total order: it only works with a selective ⊕\oplus such as min⁡\min or max⁡\max. For a window over any semigroup (a matrix product in (max⁡,+)(\max, +) 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 kk can be taken up to mkm_k times: separating capacities by their remainder modulo weight pkp_k turns the transition into a (value) maximum over a window of mk+1m_k + 1 positions, reducing cost from O(W∑kmk)\bigO(W \sum_k m_k) to O(nW)\bigO(nW).

[ ]Bounded jumps: direct versus monotone queueBrowser
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 ww even though min on a list is written in C; queue time is the same for any ww.

Convex hull trick

Now cost depends on both ii and jj, but in a special way. Our example for the rest of the lesson partitions a sequence of positive numbers a1,…,ana_1, \dots, a_n into kk 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 Si=a1+⋯+aiS_i = a_1 + \cdots + a_i, the layered recurrence is

dpk[i]=min⁡0≤j<i(dpk−1[j]+(Si−Sj)2),dp0[0]=0,dp0[i]=+∞ si i>0.dp_k[i] = \min_{0 \le j < i} \big( dp_{k-1}[j] + (S_i - S_j)^2 \big), \qquad dp_0[0] = 0, \quad dp_0[i] = +\infty \text{ si } i > 0.

Expand the square and separate what depends only on ii:

dpk[i]=Si2+min⁡j(−2Sj⏟mj⋅Si+dpk−1[j]+Sj2⏟bj).dp_k[i] = S_i^2 + \min_{j} \big( \underbrace{-2S_j}_{m_j} \cdot S_i + \underbrace{dp_{k-1}[j] + S_j^2}_{b_j} \big).

Each candidate jj is a line y=mjx+bjy = m_j x + b_j, and computing dpk[i]dp_k[i] evaluates the minimum of a set of lines at x=Six = S_i. This minimum, as a function of xx, is the lines’ lower envelope: a concave piecewise-linear function. Traversed left to right, its pieces have decreasing slopes, because for very negative xx the largest slope wins, and for very positive xx the smallest does.

The name comes from duality between lines and points: line y=mx+by = m x + b corresponds to point (m,b)(m, b), 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 x12x_{12} be the x-coordinate where ℓ1\ell_1 and ℓ2\ell_2 intersect, and analogously x13x_{13} and x23x_{23}. Since m1>m2m_1 > m_2, ℓ2<ℓ1\ell_2 < \ell_1 holds exactly for x>x12x > x_{12}; since m2>m3m_2 > m_3, ℓ2<ℓ3\ell_2 < \ell_3 holds exactly for x<x23x < x_{23}. Thus ℓ2\ell_2 is strictly minimal on interval (x12,x23)(x_{12}, x_{23}), empty if and only if x23≤x12x_{23} \le x_{12}. It remains to show x23≤x12  ⟺  x13≤x12x_{23} \le x_{12} \iff x_{13} \le x_{12}. If x13≤x12x_{13} \le x_{12}, at x12x_{12} we have ℓ3≤ℓ1=ℓ2\ell_3 \le \ell_1 = \ell_2 (because to the right of x13x_{13}, ℓ3\ell_3 beats ℓ1\ell_1), so ℓ2\ell_2 has already lost to ℓ3\ell_3 and x23≤x12x_{23} \le x_{12}. The converse is analogous: if x23≤x12x_{23} \le x_{12}, at x12x_{12} we have ℓ3≤ℓ2=ℓ1\ell_3 \le \ell_2 = \ell_1, hence x13≤x12x_{13} \le x_{12}. Cross products follow by multiplying by positive denominators.

∎

The algorithm is then a stack. Insert lines in decreasing slope order; before pushing a new ℓ\ell, while the stack’s last two ℓ1,ℓ2\ell_1, \ell_2 satisfy the criterion with ℓ3=ℓ\ell_3 = \ell, pop ℓ2\ell_2. Each line enters once and leaves at most once: O(n)\bigO(n) total. Queries have three cases:

  1. Increasing queries. Intersections between consecutive envelope pieces increase, so if xx only increases, the optimal line only advances along the envelope: a pointer that never retreats answers all queries in amortized O(n)\bigO(n). In partitioning, x=Six = S_i increases because aia_i are positive.
  2. Arbitrary queries. Binary search over intersections: O(log⁡n)\bigO(\log n) per query.
  3. 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 xx 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 O(log⁡C)\bigO(\log C) for a domain of size CC; the idea works for any family of functions intersecting pairwise at most once.
InteractiveThe lower envelope of lines
  • lower envelope
  • line removed this step
  • bands: winning line for each xx interval; the frame is the method’s interval
Line insertion
7 of 7
2.40
Query method
Lines on the envelope5 of 7
Minimum at x = 2.403.96 (ℓ1)
Method answerℓ1
Pointer advances / queries1 / 1
Naive method evaluations7 per query
Inserting ℓ6\ell_{6} makes ℓ5\ell_{5} redundant: ℓ4\ell_{4} and ℓ6\ell_{6} intersect at x=7.60x = 7.60, left of where ℓ5\ell_{5} would start winning (x=8.71x = 8.71).
Lines ℓ0,…,ℓ6\ell_0, \dots, \ell_6 are inserted in decreasing slope order. The lower envelope is the thick line, and bands below show which line wins on each interval of xx. Advance insertions: twice a line becomes redundant and the criterion's two intersections appear (the filled point lies left of the hollow point). Drag points to move lines up and down. Then slide query xx right in pointer mode, then left: why does it fail, and what does binary search cost?

Divide-and-conquer optimization

The convex hull trick needs cost linear in something involving ii. 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 M[i][j]=dpk−1[j]+C(j,i)M[i][j] = dp_{k-1}[j] + C(j, i) a matrix with one row per state ii and one column per candidate jj (with +∞+\infty where j≥ij \ge i). Let opt(i)\mathrm{opt}(i) be the leftmost argmin of row ii. If opt(i)≤opt(i+1)\mathrm{opt}(i) \le \mathrm{opt}(i + 1) for every ii, 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 opt(mid)\mathrm{opt}(mid).

Proof

Correctness follows by induction on recursion: if opt(mid)=o\mathrm{opt}(mid) = o, monotonicity guarantees opt(i)≤o\mathrm{opt}(i) \le o for i<midi < mid and opt(i)≥o\mathrm{opt}(i) \ge o for i>midi > mid, so restricting the range cannot lose the argmin. (Using leftmost argmin and min⁡\min over pairs (M,j)(M, j) also resolves ties correctly.) For cost, consider calls at the same depth dd in the recursion tree. Their row ranges are disjoint and column ranges [o0,o1],[o1,o2],…[o_0, o_1], [o_1, o_2], \dots consecutive, sharing only endpoints, so their lengths sum to at most n+2dn + 2^d. Since rows are halved, there are ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil depths, each with at most nn nonempty calls. Total O(nlog⁡n)\bigO(n \log n).

∎

For kk layers, O(knlog⁡n)\bigO(kn \log n) instead of O(kn2)\bigO(kn^2). 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: f(j)f(j), g(i)g(i) and h(i)−h(j)h(i) - h(j) satisfy it with equality. Thus dpk−1[j]dp_{k-1}[j] is harmless.
  • Costs summing over pairs. If C(j,i)=∑j<p<q≤iφ(p,q)C(j, i) = \sum_{j < p < q \le i} \varphi(p, q) with φ≥0\varphi \ge 0, then CC satisfies it. Calling P(x,y)P(x, y) the set of pairs within (x,y](x, y]: P(a,c)∪P(b,d)⊆P(a,d)P(a, c) \cup P(b, d) \subseteq P(a, d) and P(a,c)∩P(b,d)=P(b,c)P(a, c) \cap P(b, d) = P(b, c), so C(a,c)+C(b,d)=φ(unioˊn)+φ(interseccioˊn)≤C(a,d)+C(b,c)C(a, c) + C(b, d) = \varphi(\text{unión}) + \varphi(\text{intersección}) \le C(a, d) + C(b, c).
  • The squared sum is of this kind: (Si−Sj)2=∑j<p≤iap2+2∑j<p<q≤iapaq(S_i - S_j)^2 = \sum_{j < p \le i} a_p^2 + 2\sum_{j < p < q \le i} a_p a_q, a prefix function plus a sum over pairs weighted 2apaq≥02 a_p a_q \ge 0. 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, max⁡(dpk−1[j],Si−Sj)\max(dp_{k-1}[j], S_i - S_j), is not of the form f(j)+C(j,i)f(j) + C(j, i), but its argmins are also monotone; seeing why is a good exercise in this reasoning. Let j∗j^* be the leftmost argmin of row ii with finite minimum and let j<j∗j < j^*. If dpk−1[j]=+∞dp_{k-1}[j] = +\infty (a prefix too short for k−1k - 1 blocks), column jj equals +∞+\infty in every row and is never the argmin of a finite row. Otherwise, since dpk−1dp_{k-1} is nondecreasing where finite (with more numbers the best most-expensive block does not decrease), dpk−1[j]≤dpk−1[j∗]≤M[i][j∗]<M[i][j]dp_{k-1}[j] \le dp_{k-1}[j^*] \le M[i][j^*] < M[i][j], so in row ii the maximum of jj is the second term: M[i][j]=Si−SjM[i][j] = S_i - S_j. Moving to row i′>ii' > i with Δ=Si′−Si≥0\Delta = S_{i'} - S_i \ge 0, term Si′−SjS_{i'} - S_j increases by exactly Δ\Delta and M[i′][j∗]M[i'][j^*] increases by at most Δ\Delta. Therefore M[i′][j]≥M[i][j]+Δ>M[i][j∗]+Δ≥M[i′][j∗]M[i'][j] \ge M[i][j] + \Delta > M[i][j^*] + \Delta \ge M[i'][j^*], and no j<j∗j < j^* can be the argmin of row i′i'.

InteractiveMonotonicity of the optimal split
i \ j01234567891011123456789101112
  • leftmost argmin of each row and staircase
  • columns examined by divide and conquer
  • quadrangle inequality violation or incorrect split
  • cell cost within its row: darker means cheaper
0.00
Adjacent 2×2 violations0
Argmin staircasemonotone
Evaluations: divide and conquer / all40 / 78
Rows with incorrect split0
The matrix satisfies the quadrangle inequality: argmins step down and right, and divide and conquer succeeds on every row.
Matrix M[i][j]=dp1[j]+(Si−Sj)2M[i][j] = dp_1[j] + (S_i - S_j)^2 for the second layer of block partitioning with quadratic cost. Each row is colored by its own range (stronger means cheaper) and its leftmost argmin marked: they form a staircase descending rightward. Aquamarine frames are columns examined by divide and conquer in each row, far fewer than all. Raise perturbation ε\varepsilon or click cells to lower their cost: crosses mark quadrangle-inequality violations. When does the staircase break? Does divide and conquer warn when it errs?

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.

[ ]Block partitioning: direct versus divide and conquerBrowser
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 n/(2log⁡2n)n / (2\log_2 n) and on n=105n = 10^5 of order 3000. For quadratic cost the convex hull trick goes further, because slopes −2Sj-2S_j decrease and queries SiS_i increase: each layer costs O(n)\bigO(n).

[ ]Partitioning with convex hull trick in O(kn)Browser
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 O(n2)\bigO(n^2) states and O(n)\bigO(n) splits per state: O(n3)\bigO(n^3). Knuth (1971) observed the optimal search-tree root is monotone and reduced cost to O(n2)\bigO(n^2); Yao (1980) identified the abstract property justifying it. The general form, for 0≤i≤j≤n0 \le i \le j \le n, is

c(i,i)=0,c(i,j)=w(i,j)+min⁡i<r≤j(c(i,r−1)+c(r,j))(i<j),c(i, i) = 0, \qquad c(i, j) = w(i, j) + \min_{i < r \le j} \big( c(i, r - 1) + c(r, j) \big) \quad (i < j),

and call K(i,j)K(i, j) the largest rr attaining the minimum.

Proof

(1) Induct on j′−ij' - i. If i=i′i = i' or j=j′j = j', the inequality is equality. Write cr(i,j)=w(i,j)+c(i,r−1)+c(r,j)c_r(i, j) = w(i, j) + c(i, r - 1) + c(r, j).

Case i<i′=j<j′i < i' = j < j'. We must show c(i,j)+c(j,j′)≤c(i,j′)c(i, j) + c(j, j') \le c(i, j'). Let r=K(i,j′)r = K(i, j'). If r≤jr \le j, rr is a valid split for [i,j][i, j] and, using w(i,j)≤w(i,j′)w(i, j) \le w(i, j'), c(i,j)+c(j,j′)≤w(i,j′)+c(i,r−1)+c(r,j)+c(j,j′)c(i, j) + c(j, j') \le w(i, j') + c(i, r - 1) + c(r, j) + c(j, j'). By the induction hypothesis (with r≤j≤j≤j′r \le j \le j \le j' and j′−r<j′−ij' - r < j' - i), c(r,j)+c(j,j′)≤c(r,j′)+c(j,j)=c(r,j′)c(r, j) + c(j, j') \le c(r, j') + c(j, j) = c(r, j'), leaving cr(i,j′)=c(i,j′)c_r(i, j') = c(i, j'). If r>jr > j, split rr is valid for [j,j′][j, j'] and, with w(j,j′)≤w(i,j′)w(j, j') \le w(i, j'), c(i,j)+c(j,j′)≤w(i,j′)+c(i,j)+c(j,r−1)+c(r,j′)c(i, j) + c(j, j') \le w(i, j') + c(i, j) + c(j, r - 1) + c(r, j'); by induction (i≤j≤j≤r−1i \le j \le j \le r - 1), c(i,j)+c(j,r−1)≤c(i,r−1)c(i, j) + c(j, r - 1) \le c(i, r - 1), again leaving c(i,j′)c(i, j').

Case i<i′<j<j′i < i' < j < j'. Let y=K(i′,j)y = K(i', j) and z=K(i,j′)z = K(i, j'). If z≤yz \le y, zz is valid for [i,j][i, j] and yy for [i′,j′][i', j']: c(i,j)+c(i′,j′)≤w(i,j)+w(i′,j′)+c(i,z−1)+c(i′,y−1)+c(z,j)+c(y,j′)c(i, j) + c(i', j') \le w(i, j) + w(i', j') + c(i, z - 1) + c(i', y - 1) + c(z, j) + c(y, j'). The quadrangle inequality for ww and induction applied to z≤y≤j≤j′z \le y \le j \le j' give ≤[w(i,j′)+c(i,z−1)+c(z,j′)]+[w(i′,j)+c(i′,y−1)+c(y,j)]=c(i,j′)+c(i′,j)\le [w(i, j') + c(i, z - 1) + c(z, j')] + [w(i', j) + c(i', y - 1) + c(y, j)] = c(i, j') + c(i', j). If z>yz > y, use yy for [i,j][i, j] and zz for [i′,j′][i', j'], and induction on i≤i′≤y−1≤z−1i \le i' \le y - 1 \le z - 1 closes similarly.

(2) Let i+1<r≤r′≤ji + 1 < r \le r' \le j. By (1) with i<i+1≤r−1≤r′−1i < i + 1 \le r - 1 \le r' - 1: c(i,r−1)+c(i+1,r′−1)≤c(i,r′−1)+c(i+1,r−1)c(i, r - 1) + c(i + 1, r' - 1) \le c(i, r' - 1) + c(i + 1, r - 1). Adding w(i,j)+w(i+1,j)+c(r,j)+c(r′,j)w(i, j) + w(i + 1, j) + c(r, j) + c(r', j) to both sides,

cr(i,j)+cr′(i+1,j)≤cr′(i,j)+cr(i+1,j).c_r(i, j) + c_{r'}(i + 1, j) \le c_{r'}(i, j) + c_r(i + 1, j).

Take r′=K(i,j)r' = K(i, j). If r′=i+1r' = i + 1, inequality K(i,j)≤K(i+1,j)K(i, j) \le K(i + 1, j) is trivial. Otherwise, every rr valid for [i+1,j][i + 1, j] with r≤r′r \le r' satisfies cr′(i,j)≤cr(i,j)c_{r'}(i, j) \le c_r(i, j), and the preceding inequality gives cr′(i+1,j)≤cr(i+1,j)c_{r'}(i + 1, j) \le c_r(i + 1, j): no split left of r′r' is strictly better for [i+1,j][i + 1, j], so the largest optimal split of [i+1,j][i + 1, j] is at least r′r'. The other half, K(i,j−1)≤K(i,j)K(i, j - 1) \le K(i, j), is symmetric.

Cost. For fixed length L=j−iL = j - i, work is ∑i(K(i+1,i+L)−K(i,i+L−1)+1)\sum_i \big(K(i + 1, i + L) - K(i, i + L - 1) + 1\big). The sum telescopes: terms KK cancel in pairs except the first and last, between 0 and nn, leaving O(n)\bigO(n) evaluations per length. With nn lengths, O(n2)\bigO(n^2).

∎

This Knuth–Yao speedup applies directly to optimal search trees, where w(i,j)w(i, j) 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 KK, fill the table by interval length, as in every interval dynamic program.

[ ]Knuth–Yao on an alphabetic tree, and what happens with matrix chainsBrowser
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 2×22 \times 2 submatrices, Mij+Mi+1,j+1≤Mi,j+1+Mi+1,jM_{ij} + M_{i+1,j+1} \le M_{i,j+1} + M_{i+1,j}: 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 Mij>Mij′M_{ij} > M_{ij'} and Mi′j≤Mi′j′M_{i'j} \le M_{i'j'}, adding gives Mij+Mi′j′>Mij′+Mi′jM_{ij} + M_{i'j'} > M_{ij'} + M_{i'j}, contradicting the condition. Now the pieces fit:

  • The matrix of transition f(j)+C(j,i)f(j) + C(j, i) with quadrangular CC is Monge (rows are ii and columns jj). Divide-and-conquer argmin monotonicity is total monotonicity.
  • The convex hull trick’s line matrix, Mij=mjxi+bjM_{ij} = m_j x_i + b_j with decreasing mjm_j and increasing xix_i, is Monge: Mij+Mi′j′−Mij′−Mi′j=(mj−mj′)(xi−xi′)≤0M_{ij} + M_{i'j'} - M_{ij'} - M_{i'j} = (m_j - m_{j'})(x_i - x_{i'}) \le 0.
  • The Knuth–Yao quadrangle inequality is the Monge condition for ww, 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 n×mn \times m matrix with O(n+m)\bigO(n + m) evaluations, without storing the matrix. It has two phases. Reduce removes columns using a stack where the column at position rr can only be minimum for rows rr onward: if in row rr 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 nn useful columns remain after O(m)\bigO(m) 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 O(n)\bigO(n) total. Cost satisfies T(n,m)=O(n+m)+T(n/2,n)T(n, m) = \bigO(n + m) + T(n/2, n), giving O(n+m)\bigO(n + m). This theory of Monge matrices and SMAWK reduces layered partitioning to O(kn)\bigO(kn) with any quadrangular cost, not only linear ones.

[ ]SMAWK from scratchBrowser
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 nn grows by a factor of 40. In practice divide and conquer is simpler and its log⁡n\log n factor barely noticeable, so SMAWK is reserved for when log⁡n\log n 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 f(j)f(j) must not depend on rows being computed. In a single-layer recurrence, dp[i]=min⁡j<idp[j]+C(j,i)dp[i] = \min_{j < i} dp[j] + C(j, i), column jj only exists once row jj has been computed. For that “online” case with quadrangular CC there are O(nlog⁡n)\bigO(n \log n) algorithms maintaining a candidate queue and using binary search to find where each begins winning, and even O(n)\bigO(n) (Larmore and Schieber, 1991).

The Aliens trick in one paragraph

If optimal cost with exactly kk blocks, g(k)g(k), is convex in kk, the kk dimension can be removed entirely using Lagrangian relaxation: for price λ\lambda per block solve h(λ)=min⁡particiones(coste+λ⋅bloques)h(\lambda) = \min_{\text{particiones}} \big(\text{coste} + \lambda \cdot \text{bloques}\big), a single-layer dynamic program, and use binary search on the answer for the λ\lambda at which the optimal solution uses kk blocks; then g(k)=h(λ)−λkg(k) = h(\lambda) - \lambda k. Convexity guarantees this λ\lambda exists (it is a slope of gg), reducing cost from O(kn)\bigO(kn) to O(nlog⁡C)\bigO(n \log C). 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:

NeedTool
graph pathsnetworkx, scipy.sparse.csgraph.shortest_path and floyd_warshall
stable log-sum-expscipy.special.logsumexp, np.logaddexp, torch.logsumexp
(min⁡,+)(\min, +) matrix productNumPy broadcasting: (A[:, :, None] + B[None, :, :]).min(axis=1)
hidden Markov models and CRFsvectorized forward, Viterbi and forward-backward in PyTorch
differentiable structured dynamic programminglibraries such as Torch-Struct (Rush, 2020), which parameterize the semiring
[ ]NumPy and SciPy building blocksBrowser
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 n×n×nn \times n \times n, so memory is O(n3)\bigO(n^3): with n=120n = 120 it is 14 MB, with n=1000n = 1000 it would be 8 GB. For large matrices split into row blocks. The naive log-sum-exp version returns −∞-\infty: each e−800e^{-800} 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

QuizIs it a semiring?
Which of these structures are semirings with the stated identities?

More than one answer may be correct.

NumericWalks of length 10
The undirected graph with vertices 1,2,3,41, 2, 3, 4 has edges {1,2}\{1,2\}, {2,3}\{2,3\}, {3,4}\{3,4\}, {4,1}\{4,1\} and chord {1,3}\{1,3\}. How many walks of exactly length 10 (10 edges, repetitions allowed) go from vertex 1 to vertex 3?
NumericThe most expensive block
Partition sequence 1,2,3,4,5,61, 2, 3, 4, 5, 6 into exactly 3 nonempty contiguous blocks to minimize the sum of the heaviest block. What is that sum?
QuizWhich optimization applies? (1)
A robot moves through positions 0,1,…,n−10, 1, \dots, n - 1 with jumps of at most ww positions; it pays c>0c > 0 per distance unit and hih_i to stop at ii: dp[i]=hi+min⁡i−w≤j<i(dp[j]+c (i−j))dp[i] = h_i + \min_{i - w \le j < i} \big(dp[j] + c\,(i - j)\big). Which technique gives O(n)\bigO(n) total for any ww?
QuizWhich optimization applies? (2)
Let x1<x2<⋯<xnx_1 < x_2 < \cdots < x_n and dp[i]=min⁡j<i(dp[j]+(xi−xj)2+K)dp[i] = \min_{j < i} \big(dp[j] + (x_i - x_j)^2 + K\big), with dp[0]=0dp[0] = 0 and constant K>0K > 0. Which technique reduces this single-layer recurrence to O(n)\bigO(n)?
QuizWhich optimization applies? (3)
Partition a permutation σ\sigma of 1..n1..n into kk contiguous blocks to minimize the sum over blocks of inversion counts: dpk[i]=min⁡j<i(dpk−1[j]+inv(j,i))dp_k[i] = \min_{j < i}\big(dp_{k-1}[j] + \mathrm{inv}(j, i)\big), where inv(j,i)\mathrm{inv}(j, i) counts pairs p<qp < q in (j,i](j, i] with σp>σq\sigma_p > \sigma_q. Which technique is correct?
QuizWhich optimization applies? (4)
Matrix chain: c(i,j)=min⁡i<r<j(c(i,r)+c(r,j)+pi pr pj)c(i, j) = \min_{i < r < j}\big(c(i, r) + c(r, j) + p_i\,p_r\,p_j\big) with c(i,i+1)=0c(i, i+1) = 0. Can the split be restricted to [K(i,j−1),K(i+1,j)][K(i, j-1), K(i+1, j)] to obtain O(n2)\bigO(n^2)?
QuizStrassen in the tropical semiring
Why does Strassen's algorithm not calculate matrix products over (min⁡,+)(\min, +)?
ProofQuadrangle inequality implies monotone argmins
Prove: If MM satisfies Mij+Mi′j′≤Mij′+Mi′jM_{ij} + M_{i'j'} \le M_{ij'} + M_{i'j} for all i<i′i < i' and j<j′j < j', and opt(i)\mathrm{opt}(i) is row ii's leftmost argmin, then opt(i)≤opt(i′)\mathrm{opt}(i) \le \mathrm{opt}(i') whenever i<i′i < i'.
0
Let i<i′i < i'. Assume for contradiction that j:=opt(i′)<j′:=opt(i)j := \mathrm{opt}(i') < j' := \mathrm{opt}(i).

Step 1 of 3. What do you know about row ii comparing columns jj and j′j'?

ProofFloyd–Warshall and Kleene are the same dynamic program
Prove: Let A\mat{A} be the weight matrix of a graph with nodes 1,…,n1, \dots, n over a closed semiring, and Dij(k)D^{(k)}_{ij} the semiring sum of weights of all paths from ii to jj whose intermediate nodes lie in {1,…,k}\{1, \dots, k\}. Then Dij(k)=Dij(k−1)⊕Dik(k−1)⊗(Dkk(k−1))∗⊗Dkj(k−1)D^{(k)}_{ij} = D^{(k-1)}_{ij} \oplus D^{(k-1)}_{ik} \otimes \big(D^{(k-1)}_{kk}\big)^{*} \otimes D^{(k-1)}_{kj}, and this recurrence is Floyd–Warshall over (min⁡,+)(\min, +) and Kleene's algorithm over the language semiring.
0
Fix kk and classify paths from ii to jj with intermediates in {1,…,k}\{1, \dots, k\} by how often they pass through kk as an intermediate node.

Step 1 of 4. What do paths not using kk as an intermediate contribute?

CodeConvex hull trick in linear time
Implement minimos_rectas(rectas, consultas). Lines are integer pairs (m, b) with strictly decreasing slopes; queries are integers in nondecreasing order. Return the list of min⁡j(mjx+bj)\min_j (m_j x + b_j) for each query xx in O(n+q)\bigO(n + q) 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 []
Shift+Enter to run
CodePaths with exactly k edges
Implement 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 (min⁡,+)(\min, +) product, the semiring identity and binary exponentiation so k may be 101210^{12}.
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 W
Shift+Enter to run

Summary

Key idea
A dynamic program is a topological traversal aggregating paths with two operations; the semiring determines what is computed and distributivity makes it efficient. Optimizations improving on O(n2)\bigO(n^2) all exploit the same Monge structure in the transition matrix, and applying them without it fails silently.
  • A semiring is a ring without subtraction. Dynamic programming over a DAG computes ⨁π⨂e∈πw(e)\bigoplus_{\pi} \bigotimes_{e \in \pi} w(e) using ∣E∣\abs{E} products: (min⁡,+)(\min, +) gives shortest paths, (+,×)(+, \times) counts or sums probabilities, (max⁡,×)(\max, \times) is Viterbi, and logarithmic is stable forward, a smooth maximum tending to (max⁡,+)(\max, +) as T→0T \to 0.
  • 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: Ak\mat{A}^k sums walks with exactly kk edges and is computed with O(log⁡k)\bigO(\log k) products. Strassen does not work without subtraction.
  • Monotone queue for window minima, amortized O(n)\bigO(n). Convex hull trick when cost is ajxi+bja_j x_i + b_j: 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 ww, from O(n3)\bigO(n^3) to O(n2)\bigO(n^2); SMAWK finds minima of all rows of a Monge matrix in O(n+m)\bigO(n + m).
  • Before trusting an optimized version, compare it against the direct one on small random cases.