Range query data structures
Build a range-query toolkit: prefix sums, Fenwick and segment trees, lazy propagation, sparse tables, LCA and augmented trees.
After this lesson you can
- Choose a range-query structure for the aggregate and updates required.
- Implement a Fenwick tree and explain the arithmetic of i & (−i).
- Design a lazy segment tree by identifying aggregate and update monoids.
- Answer RMQ in O(1) with a sparse table and reduce LCA to RMQ.
- Augment a balanced tree for order statistics and interval queries.
Before you start
Motivation: aggregates over changing intervals
A pattern appears whenever a program stores a sequence and someone asks about pieces of it: what is their sum or minimum, how many are there, where is the -th? If the sequence never changed, precomputation would suffice. If nobody asked, storing it would suffice. The hard part is supporting both at once.
- Window metrics. An observability dashboard stores request counts and latency minute by minute. Questions ask for aggregates over arbitrary windows (“requests between 10:00 and 10:45”, “worst latency in the last hour”), while data keep arriving. If a histogram of latency buckets is also stored, the 99th percentile is “the bucket where the cumulative sum reaches 99% of the total”: a prefix sum to invert.
- Cumulative frequencies in a compressor. Adaptive arithmetic coding assigns each symbol interval of cumulative frequencies, then increments its frequency after encoding. Each symbol needs a prefix sum and point update, and the decoder performs the inverse search: which symbol has the cumulative frequency just read. This is exactly the problem Peter Fenwick solved in 1994.
- Lines of code. An editor must translate “line 12,345” to a byte position and back. The starting position of line is the sum of the lengths of the preceding lines, and each keystroke changes one length. VS Code’s text buffer, rewritten in 2018, is a red-black tree of pieces in which each node stores the length and newline count of its left subtree: an augmented tree, the final protagonist of this lesson.
All three ask for an aggregate over an interval of a changing sequence. The answer is a ladder of structures, each buying something different: prefix sums (static, per query), Fenwick tree (sums with updates, very short code), segment tree (any associative aggregate and range updates), sparse table (minima in on fixed data), and augmented trees (keys inserted and deleted rather than fixed positions). Finally, the same idea leaves the array for the plane and space: quadtrees and octrees.
| Structure | Preprocessing | Query | Update | Aggregates |
|---|---|---|---|---|
| Prefix sums | rebuild, | with inverse (groups): sum, XOR | ||
| Fenwick tree | point, | inverse for ranges; prefixes of any commutative monoid | ||
| Segment tree | point or range, | any monoid | ||
| Sparse table | none | associative and idempotent: min, max, gcd | ||
| Augmented tree | insert and delete keys, | anything computable from children |
Prefix sums: the static case
Let be a fixed sequence. Its prefix sums are
and every interval sum is a subtraction: . Preprocessing with additions turns each query into two reads. In code, with zero-based indices and half-open ranges, the formula is even cleaner: the sum of a[l:r] is P[r] - P[l].
Subtraction is both the key and the limitation. It works because addition has an inverse: can be rearranged to obtain the part of interest. With minimum nothing can be isolated: if , the global minimum is already reached before , both prefixes have the same value and say nothing about the minimum of , which can be any value at least that large. Every aggregate forming a group (associative, with identity and inverses), such as addition, XOR or multiplication of nonzero numbers, admits prefix sums; those forming only a monoid, such as minimum, need other ideas.
Prefix sums are the scan operation you will see parallelized in lesson 26, and appear in disguise in many places: a histogram’s cumulative distribution function, roulette-wheel sampling from a discrete distribution (a prefix sum and binary search), or the forward step of CTC, accumulating probabilities along the sequence.
In two dimensions
For a matrix , define as the sum of the rectangle formed by the first rows and columns. By inclusion-exclusion,
and the sum of any rectangle with rows and columns is
The two subtractions remove the top and left strips, and since their common corner was removed twice, it is added once. In computer vision this table is called an integral image (summed-area table, Crow, 1984): Viola and Jones’s face detector (2001) used it to evaluate thousands of rectangular features with four reads per rectangle regardless of size. In dimensions the formula has alternating-sign terms.
Differences: range updates over static data
The inverse problem is also common: many “add to ” updates and one read at the end. The difference array turns each range update into two point updates, and , because differences within the range do not change. A prefix sum of reconstructs . Difference and prefix sum are inverses, like derivative and integral, and combining them will be the key to range Fenwick trees. But once updates and queries are interleaved, both techniques cost per operation on their bad side. A middle ground is needed.
The Fenwick tree
The idea is to store partial block sums, neither all prefix sums (expensive to update) nor individual elements (expensive to sum). Fenwick’s block choice is as economical as possible: one array the same size as the data, no pointers, with blocks read from the binary representation of the index.
Odd indices store one element; multiples of 2 that are not multiples of 4 store two; multiples of 4 that are not multiples of 8 store four; and so on. In the figure each is a horizontal block, placed in the row of its .
The lowest bit in two’s complement
In two’s complement, is calculated by inverting every bit and adding 1. If is written (a prefix , the lowest set bit and zeros), then and, on adding 1, the carry travels through the ones and stops at zero: . Bitwise AND with clears the prefix (), keeps bit and leaves zeros below:
With : in five bits, and . The interactive’s right panel performs this calculation at every step. Python integers have arbitrary precision but behave like two’s complement with infinitely many leading ones, so i & -i works the same way.
Query: remove the lowest set bit
Proof
Subtracting clears the lowest set bit of without touching the others, so each step reduces the number of set bits by one and the sequence ends at after steps. The block of is : consecutive blocks fit without gaps or overlap, from down to .
∎With : covers , covers and covers . Three set bits, three summands. This is the binary representation of 13, , read from bottom to top.
Update: add the lowest set bit
Changing requires correcting every block containing . That there are few, and that adding the lowest set bit finds them, is the heart of the structure.
Proof
Let . The block of , with , contains if and only if . Write , where are the bits of above . Then and the condition says : the bits of above are and bit of is 0. Conversely, for each with bit of zero there is exactly one such ,
which copies the high bits of , sets bit to 1 and leaves zeros below. Thus the blocks containing are , one for each zero bit of .
It remains to show that the chain visits them in order. If is the lowest zero bit of , adding 1 to turns the ones below into zeros and sets bit : . And if , adding propagates a carry through the ones of above bit and stops at the next zero bit of : the result is . The chain therefore visits for the zero bits of in increasing order, and since increase with , it stops on exceeding . There is at most one per .
∎With , has zeros at bits 0, 1, 3 and 4, and the blocks are , , and : chain . In the figure, the vertical through crosses exactly those four blocks.
Together the two theorems give a useful corollary: if , exactly one of the blocks used by the query contains (because they partition ), and that block is in the update chain of . This is why an update followed by a query is correct: the change in enters the sum exactly once. If , no query block contains , so the change does not enter.
Construction, k-th search and ranges
Construction in . Instead of updates (), copy into and traverse adding to . By the preceding theorem, is the smallest block strictly containing that of : its “parent”. When is processed, all its children, which are smaller than , have already contributed to it.
The k-th in . If are nonnegative, prefix sums are increasing and it makes sense to find the least with : the symbol for a cumulative frequency, percentile bucket or line containing a byte. Binary search on would make queries costing . But the tree lets us decide answer bits from highest to lowest with one access per bit: maintain position (initially 0) with , and for try advancing to . Since is a sum of powers larger than , it is a multiple of , so and is exactly the sum of . If and that block sums to less than the remainder, advance and subtract it; otherwise the -th lies inside that block and we try one half as long. At the end the answer is . This is binary search on the answer using blocks the tree already summed.
Ranges. The sum of is : two queries. For “add in ” with point queries, one Fenwick tree over the difference array suffices. To support both range updates and range queries there is a two-tree trick: if is the difference array, . Maintain two Fenwick trees, one with and one with ; it is implemented in the lab below.
The segment tree
The segment tree applies divide and conquer to the array itself and stores the result of each subproblem.
It has nodes, height , and is stored like a heap: root at position 1 and children of at and ( positions suffice for any ). The three operations are short recursions:
- Build: each node combines its children’s aggregates, .
- Update : change the leaf and recombine its ancestors, at most .
- Query : from the root, a node disjoint from the range returns , one contained returns its aggregate without descending, and a partial one combines its two children’s answers in order.
That a query costs is not obvious: a long range covers many leaves. The key is that each level can have only two partial nodes, those containing range boundaries; you will prove this step by step in the exercises. The range is expressed as the union of at most contained nodes.
Why a monoid is enough
Associativity is exactly what allows splitting the interval wherever suits the tree, not the user. Identity is only needed for disjoint nodes. Commutativity is not required, provided children are combined in order, left before right. This opens the door to aggregates that are not numbers:
Other useful monoids include matrix product (a node stores the ordered product of matrices in its interval, enabling affine transformation composition or evaluating linear recurrences over a range), composition of functions of a closed type, and the pair (minimum, number of occurrences).
Lazy propagation
Now suppose updates also cover ranges: “add 3 to every element of ”. Updating leaf by leaf costs . The lazy idea mirrors querying: if a node lies entirely inside the range, update its aggregate and record a tag there with the pending update for descendants, without visiting them. The tag moves down to children only when a later operation needs to enter that node.
For this to work, updates must satisfy two algebraic conditions worth writing down, because they capture everything that can go wrong.
The key operation is push: before descending to children of a node with tag , apply to each child’s aggregate, compose it with the child’s existing tag, , and reset the parent tag to identity. Composition order matters: what the child already had pending happened before what arrives from the parent.
Proof
Initially all tags are identity and aggregates exact. It suffices to see the three operations preserve the invariant. An operation only enters a node after pushing all ancestor tags, so at that moment they are all identity. (1) Apply to node contained in the range: new aggregate is the real one because is an endomorphism applied to all interval elements. For descendant of , the invariant expression gains outside its existing tags, exactly what happened to its elements: pending operations first, then . (2) Push from changes to and to in each child , and sets : for and every descendant of the total composition stays unchanged. (3) Recombine is done with and no tags above, when children are already exact.
∎The table collects common cases. In all, cost per operation is : the same nodes as a query are visited, plus one push per partial node.
| Aggregate | Update | Tag | Composition “ after ” |
|---|---|---|---|
| minimum | add | ||
| minimum or maximum | assign | most recent wins, | |
| sum with length: | add : | ||
| sum with length | affine : | ||
| minimum and maximum | affine with of any sign | as above; if , minimum and maximum swap |
Two observations. A sum aggregate must carry interval length: “add ” changes the sum by , and without it is not an endomorphism of the sum monoid. The affine family also handles the most error-prone case, mixing add and assign: “add ” is , “assign ” is , and the noncommutative final-column composition automatically does the right thing. Assign 5 then add 2 is ; add 2 then assign 5 is .
A rigor detail about row two. With minimum as aggregate, “assign ” is constant map , which respects () but does not fix the identity: it maps to . This does no harm because the tree only applies tags to nonempty-interval aggregates, never to , which appears only as the answer for disjoint nodes; to satisfy the definition literally, define assignment as on finite values and on . The same applies to affine maps with on minima and maxima. For sum and length the problem does not arise: identity maps to .
The experiment shows why such errors are treacherous: incorrect composition does not spoil the updated node’s aggregate (calculated by applying the new tag to its value), but the tag it stores for its children. Queries answered by that entire node remain correct; only those descending below it fail, sometimes much later. Tests should therefore mix random operations and compare against a naive version, as in the lab.
Sparse tables: minima in
If data do not change and minimum is requested (the range minimum query, RMQ), one can improve on . The sparse table precomputes the minimum of every power-of-two-length window:
Level has entries and there are levels: in time and memory. To query , take and cover the ends with two windows of length , one starting at and one ending at :
Proof
Since , both windows lie within and together cover it. Call the portion covered only by the first, the overlap and the portion covered only by the second (which occur in that order, with possibly empty; if is empty there is nothing to prove). The first window is and the second , so associativity and idempotence give .
∎Commutativity is unnecessary, but idempotence is essential: with sum, overlap would be counted twice. Minimum, maximum, greatest common divisor, bitwise AND and OR are idempotent; sum, XOR and product are not. For associative non-idempotent operations there is a disjoint sparse table, which stores aggregates toward both sides of each split point at every level and answers using two nonoverlapping windows, also in after . To calculate in , use a machine instruction (bit_length in Python, __builtin_clz in C) or a precomputed table.
Linear preprocessing with blocks
Can preprocessing be reduced to without losing queries? Yes, by splitting the array into blocks of size :
- Between blocks: each block’s minimum forms an array of elements, and its sparse table costs .
- Prefixes and suffixes: minimum of each prefix and suffix of each block, in total.
- Inside one block: the hard case, when and fall in the same block.
A query crossing multiple blocks is the first block’s suffix, the sparse table over intermediate blocks and the last block’s prefix: . For the third case, Bender and Farach-Colton (2000) observed that in ±1 arrays, where consecutive elements differ by exactly 1, the minimum position of any subrange of a block depends only on the sequence of rises and falls, not the initial value. There are at most distinct sequences, and answers to all their subqueries can be precomputed in . Each block stores its sequence number and a query is a table read. Total: preprocessing and per query for ±1 RMQ. The next section shows where ±1 arrays arise and how they also solve general RMQ.
LCA and RMQ: two sides of the same problem
In a rooted tree, the lowest common ancestor is the deepest node that is an ancestor of both (a node counts as its own ancestor). It is fundamental in phylogenies, class hierarchies, version-control systems (a merge base is a common ancestor), and any tree-distance query, because
Climbing from both nodes until they meet costs the tree height, which can be . The reduction between LCA and RMQ turns it into a minimum query:
- The Euler tour is the sequence of nodes written by a depth-first traversal, recording each node on entry and whenever returning from a child. It has entries, since each of the edges is traversed twice.
- Let be the position of the first occurrence of in .
- Then is the minimum-depth node in between and .
The reason is the parenthesis structure of depth-first traversal (the parenthesis theorem in lesson 18): traversal enters a node’s subtree, visits it completely without leaving, then returns to the parent. Between the first appearances of and the traversal does not leave the LCA’s subtree, so it never passes anything shallower and must pass the LCA itself to go from the branch to the branch. You will prove this in detail in the exercises.
The depth profile is a ±1 array, the case the block algorithm solves in and . Thus LCA has linear preprocessing and constant queries. The circle also closes in reverse: general RMQ reduces to LCA through the array’s Cartesian tree, whose root is the minimum’s position and whose left and right subtrees are Cartesian trees of the two halves. The minimum of is at of that tree, built in with a stack. General RMQ → LCA → ±1 RMQ: linear time and constant queries for any array. The first optimal LCA algorithms, by Harel and Tarjan (1984) and Schieber and Vishkin (1988), were notoriously hard to implement; Bender and Farach-Colton (2000) gave this simple version, a sequentialization of a parallel algorithm by Berkman, Breslauer, Galil, Schieber and Vishkin (1989).
Binary lifting
In practice another technique competes with a sparse table on the Euler tour: binary lifting. Precompute , the ancestor of levels up, with recurrence , in . To climb levels, decompose in binary and take one jump per set bit: the same idea as fast exponentiation, with the parent function instead of a number and composition instead of multiplication. For LCA, equalize depths and then climb from both nodes together with decreasing jumps while their ancestors differ: per query. It is slower than a sparse table but also answers “the -th ancestor” and extends to path aggregates (minimum edge weight between and , for example).
Augmented trees
So far positions were fixed: element 7 stays seventh forever. But many range queries concern keys: how many latencies lie between 120 and 300 ms, what is the median of observed prices, which reservations overlap this interval. Inserting a new key shifts all following positions, which an array handles poorly. The solution is to store aggregates in a balanced binary search tree.
Proof
Changing at a node can only change at its ancestors, of which there are : recompute them bottom-up. Insertion and deletion modify the tree in two places: the root-to-inserted-or-deleted-node path, recomputed this way, and rotations. A rotation changes only the subtrees of the two nodes exchanging positions, so recompute at those two, lower node first; ancestors do not change because their subtree still contains the same nodes. A red-black tree has at most two rotations per insertion and three per deletion.
∎The statement also says what cannot be maintained. Node depth depends on ancestors rather than children, and a rotation changes it for an entire subtree. A node’s global position (rank) changes for every larger-key node whenever a small key is inserted. Neither is an augmented field; rank, however, can be computed in from sizes.
The order-statistic tree
The canonical example stores , the number of nodes in ‘s subtree, with . With it:
- select, the key of rank : at node , let . If , it is ; if , find the -th on the left; if , the -th on the right.
- rank, how many keys are smaller than : while descending in search of , whenever turning right add the left subtree and node.
- Count in a range: the number of keys in is .
On insertion increment along the entire descent path and, in each rotation raising above , set (the entire subtree now hangs from ) and recompute from its new children. Forget those two lines and the tree remains a valid red-black tree with working searches, but select and rank return garbage. You will see this in the lab.
When keys are known beforehand (or can be processed offline), a simpler and faster alternative exists: compress keys to by order and use a Fenwick tree of frequencies. “Count keys in a range” is a range sum and select is the -th search. Fenwick cannot accept keys outside the initial universe; an augmented tree can.
The interval tree
To store intervals and ask which overlap a given interval, use a red-black tree ordered by where each node stores , its subtree’s greatest right endpoint: . It is an augmented field, so it is maintained at no extra asymptotic cost. To find an interval overlapping :
- if overlaps, return it;
- if , descend left;
- otherwise descend right.
Descending right when the left maximum is less than is clearly safe: everything on the left ends earlier. The other decision is subtler. If , there is an interval on the left with . If no left interval overlaps the query, neither does , and since it ends after , it must start after : . All right intervals start later still (the tree is ordered by ), so they do not overlap either. Going left never loses an answer. One search costs , and listing the overlaps costs .
Spatial ranges: quadtrees and octrees
Everything above aggregates intervals on a line. In the plane the natural questions are “how many points are in this rectangle?” or “which point is closest to this one?”. Two-dimensional prefix sums solve the first if points live on a fixed grid. For arbitrary coordinates, hierarchical blocks generalize by splitting space.
Subdivision is adaptive: where many points cluster the tree is deep, and where none exist it remains a large empty cell. The cost is that depth depends not on point count but on their proximity. With capacity 1, two points at distance in a square of side may require many subdivisions: a cell containing both has diagonal at least , so they separate at latest when cell diagonal drops below ; if both fall in a small cell of the hierarchy with no dividing line between them until deep down, nearly that depth is needed. Depth is therefore on the order of ; de Berg and coauthors (Computational Geometry, chapter 14) give bound and prove a tree of depth has nodes. Two almost coincident points can generate a very long chain of cells with one useful child; real implementations therefore cap depth or compress chains.
Range queries. Recursion matches the segment tree: prune disjoint cells; use the aggregate of contained cells; descend into partial cells. Partial cells cross the rectangle boundary, and at level (side in the unit square) a boundary of length crosses on the order of cells. With reasonably distributed points the tree has depth near and summing across levels gives on the order of boundary cells, plus answers if listing them. This is not a worst-case guarantee: k-d trees split at the median on alternating axes and guarantee in the plane.
Nearest neighbor. Traverse the tree with a priority queue ordered by the query point’s distance to each cell, pruning any cell farther away than the best candidate found. This is geometry-guided branch and bound.
Cell aggregation: Barnes-Hut. Computing gravitational (or electrostatic) force exerted by bodies on each one costs . Barnes and Hut (1986) observed that from far away, a cell with many bodies attracts almost like a single body with their total mass at their center of mass, and that aggregate is a monoid: the pair (mass, mass times position) adds. For each body traverse the octree from the root: if cell side and distance to its center of mass satisfy , use the aggregate; otherwise descend. With reasonable distributions each body interacts with cells and the total is ; trades accuracy for speed. The same trick accelerates t-SNE: van der Maaten’s Barnes-Hut version (2014), used by scikit-learn by default, approximates t-SNE repulsive forces with a quadtree, and its parameter angle (0.5 by default) is this . Greengard and Rokhlin’s fast multipole method (1987) goes a step further, with series expansions instead of point masses, reducing to .
Implementation from scratch
The lab builds a small range-query library and tests it by properties: each structure faces a naive NumPy version across thousands of random operations. With these structures errors are rarely in cases one imagines, but in operation combinations that only arise randomly. First, one- and two-dimensional prefix sums and the difference array.
import numpy as np
def prefijas(a):
"""P[i] = a[0] + ... + a[i-1], con P[0] = 0: la suma de a[l:r] es P[r] - P[l]."""
P = [0] * (len(a) + 1)
for i, x in enumerate(a):
P[i + 1] = P[i] + x
return P
def prefijas_2d(A):
"""S[i][j] = suma del rectángulo A[0:i, 0:j]; una fila y una columna de ceros delante."""
n, m = len(A), len(A[0])
S = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
S[i + 1][j + 1] = A[i][j] + S[i][j + 1] + S[i + 1][j] - S[i][j]
return S
def suma_rect(S, r0, c0, r1, c1):
"""Suma de A[r0:r1, c0:c1] por inclusión-exclusión: cuatro lecturas."""
return S[r1][c1] - S[r0][c1] - S[r1][c0] + S[r0][c0]
def aplicar_diferencias(n, actualizaciones):
"""Cada (l, r, v) suma v a a[l:r]: dos marcas por actualización y una suma prefija al final."""
D = [0] * (n + 1)
for l, r, v in actualizaciones:
D[l] += v
D[r] -= v
return prefijas(D)[1:n + 1]
rng = np.random.default_rng(0)
a = rng.integers(-50, 50, size=1000)
P = prefijas(a.tolist())
for _ in range(200):
l, r = sorted(rng.integers(0, 1001, size=2))
assert P[r] - P[l] == a[l:r].sum()
A = rng.integers(0, 10, size=(60, 80))
S = prefijas_2d(A.tolist())
for _ in range(200):
r0, r1 = sorted(rng.integers(0, 61, size=2))
c0, c1 = sorted(rng.integers(0, 81, size=2))
assert suma_rect(S, r0, c0, r1, c1) == A[r0:r1, c0:c1].sum()
ups = [(int(l), int(r), int(v)) for l, r, v in zip(rng.integers(0, 500, 300), rng.integers(500, 1001, 300), rng.integers(-5, 6, 300))]
ref = np.zeros(1000, dtype=int)
for l, r, v in ups:
ref[l:r] += v
assert np.array_equal(aplicar_diferencias(1000, ups), ref)
print("1D: 200 sumas de rango correctas, dos lecturas cada una")
print("2D: 200 rectángulos correctos, cuatro lecturas cada uno")
print("diferencias: 300 actualizaciones de rango con 600 marcas y una sola pasada")The Fenwick tree, one-indexed inside the class, with linear construction, -th search and the two-tree range variant. The final part counts how many indices each operation touches in a tree of positions.
class Fenwick:
"""Árbol de Fenwick con índices desde 1: t[i] guarda la suma de a(i - lowbit(i), i]."""
def __init__(self, n):
self.n = n
self.t = [0] * (n + 1)
@classmethod
def desde(cls, valores):
"""Construcción en O(n): cada t[i] se vuelca en su padre i + lowbit(i)."""
f = cls(len(valores))
f.t[1:] = list(valores)
for i in range(1, f.n + 1):
j = i + (i & -i)
if j <= f.n:
f.t[j] += f.t[i]
return f
def sumar(self, i, delta): # a[i] += delta
while i <= self.n:
self.t[i] += delta
i += i & -i
def prefijo(self, i): # a[1] + ... + a[i]
s = 0
while i > 0:
s += self.t[i]
i -= i & -i
return s
def rango(self, l, r): # a[l] + ... + a[r]
return self.prefijo(r) - self.prefijo(l - 1)
def kesimo(self, k):
"""Menor i con prefijo(i) >= k (frecuencias no negativas). Devuelve n + 1 si no existe."""
pos, paso = 0, 1 << self.n.bit_length()
while paso:
nxt = pos + paso
if nxt <= self.n and self.t[nxt] < k:
pos, k = nxt, k - self.t[nxt]
paso >>= 1
return pos + 1
class FenwickRango:
"""Sumar v en [l, r] y sumar a[l..r], ambas en O(log n), con dos Fenwick sobre las diferencias."""
def __init__(self, n):
self.b1, self.b2, self.n = Fenwick(n), Fenwick(n), n
def sumar_rango(self, l, r, v):
for i, w in ((l, v), (r + 1, -v)):
if i <= self.n:
self.b1.sumar(i, w)
self.b2.sumar(i, w * (i - 1))
def prefijo(self, i):
return self.b1.prefijo(i) * i - self.b2.prefijo(i)
def rango(self, l, r):
return self.prefijo(r) - self.prefijo(l - 1)
rng = np.random.default_rng(1)
n = 1000
a = rng.integers(0, 20, size=n + 1); a[0] = 0 # a[0] no se usa: índices desde 1
f = Fenwick.desde(a[1:].tolist())
for paso in range(3000):
op = rng.integers(3)
if op == 0:
i, d = int(rng.integers(1, n + 1)), int(rng.integers(0, 10))
f.sumar(i, d); a[i] += d
elif op == 1:
l, r = sorted(rng.integers(1, n + 1, size=2))
assert f.rango(int(l), int(r)) == a[l:r + 1].sum()
else:
c = np.cumsum(a)
k = int(rng.integers(1, c[-1] + 1))
assert f.kesimo(k) == int(np.searchsorted(c, k)), k
print("Fenwick: 3000 operaciones mezcladas (sumar, rango, k-ésimo) coinciden con NumPy")
g = FenwickRango(n)
b = np.zeros(n + 1, dtype=np.int64)
for paso in range(3000):
l, r = sorted(int(x) for x in rng.integers(1, n + 1, size=2))
if rng.random() < 0.5:
v = int(rng.integers(-9, 10))
g.sumar_rango(l, r, v); b[l:r + 1] += v
else:
assert g.rango(l, r) == b[l:r + 1].sum()
print("Fenwick de rangos: 3000 operaciones correctas")
def accesos_prefijo(i):
c = 0
while i > 0:
c += 1; i -= i & -i
return c
def accesos_sumar(i, n):
c = 0
while i <= n:
c += 1; i += i & -i
return c
N = 1 << 20
muestra = rng.integers(1, N + 1, size=20000)
print(f"n = 2^20: prefijo visita en media {np.mean([accesos_prefijo(int(i)) for i in muestra]):.2f} índices "
f"(máx {max(accesos_prefijo(int(i)) for i in muestra)}); sumar, {np.mean([accesos_sumar(int(i), N) for i in muestra]):.2f}")For a random 20-bit index, a query touches about 10 indices on average (set bits, half of 20) and an update about 11 (zero bits of plus the upper one). Far fewer than the million elements underneath.
Now the generic segment tree. The class knows nothing about minima or sums: it receives the monoid (op, e) and update family (aplicar, componer, ident), just like the definition. componer(g, f) means “first , then ”.
import math
class LazySegTree:
"""Árbol de segmentos sobre un monoide (op, e) con actualizaciones (aplicar, componer, ident).
Rangos semiabiertos [l, r) y raíz en el nodo 1."""
def __init__(self, valores, op, e, aplicar, componer, ident):
self.op, self.e, self.aplicar, self.componer, self.ident = op, e, aplicar, componer, ident
self.n = len(valores)
self.agg = [e] * (4 * self.n)
self.tag = [ident] * (4 * self.n)
self._construir(1, 0, self.n, valores)
def _construir(self, x, lo, hi, v):
if hi - lo == 1:
self.agg[x] = v[lo]
return
mid = (lo + hi) // 2
self._construir(2 * x, lo, mid, v)
self._construir(2 * x + 1, mid, hi, v)
self.agg[x] = self.op(self.agg[2 * x], self.agg[2 * x + 1])
def _poner(self, x, f): # f llega a x: actualiza su agregado y la deja pendiente para sus hijos
self.agg[x] = self.aplicar(f, self.agg[x])
self.tag[x] = self.componer(f, self.tag[x]) # primero lo que había, después f
def _empujar(self, x):
if self.tag[x] != self.ident:
self._poner(2 * x, self.tag[x])
self._poner(2 * x + 1, self.tag[x])
self.tag[x] = self.ident
def actualizar(self, l, r, f, x=1, lo=0, hi=None):
hi = self.n if hi is None else hi
if r <= lo or hi <= l:
return
if l <= lo and hi <= r:
self._poner(x, f)
return
self._empujar(x)
mid = (lo + hi) // 2
self.actualizar(l, r, f, 2 * x, lo, mid)
self.actualizar(l, r, f, 2 * x + 1, mid, hi)
self.agg[x] = self.op(self.agg[2 * x], self.agg[2 * x + 1])
def consultar(self, l, r, x=1, lo=0, hi=None):
hi = self.n if hi is None else hi
if r <= lo or hi <= l:
return self.e
if l <= lo and hi <= r:
return self.agg[x]
self._empujar(x)
mid = (lo + hi) // 2
return self.op(self.consultar(l, r, 2 * x, lo, mid), self.consultar(l, r, 2 * x + 1, mid, hi))
# Instancia 1: mínimo con «sumar v». Las actualizaciones son m -> m + v y componer es sumar.
def min_suma(valores):
return LazySegTree(valores, min, math.inf, lambda v, m: m + v, lambda v2, v1: v1 + v2, 0)
# Instancia 2: suma con actualizaciones afines x -> a x + b, que incluyen «sumar v» = (1, v) y «asignar c» = (0, c).
# El agregado lleva la longitud: (s, len). Composición: (a2, b2) después de (a1, b1) = (a2 a1, a2 b1 + b2).
def suma_afin(valores, componer=None):
op = lambda p, q: (p[0] + q[0], p[1] + q[1])
aplicar = lambda f, p: (f[0] * p[0] + f[1] * p[1], p[1])
bien = lambda f2, f1: (f2[0] * f1[0], f2[0] * f1[1] + f2[1])
return LazySegTree([(v, 1) for v in valores], op, (0, 0), aplicar, componer or bien, (1, 0))
def prueba(fabrica, consulta_ref, ops=3000, n=300, semilla=2, afines=False):
"""Operaciones al azar contra NumPy. Devuelve el número de la primera operación que falla, o None."""
rng = np.random.default_rng(semilla)
ref = rng.integers(-20, 20, size=n).astype(np.int64)
st = fabrica(ref.tolist())
for k in range(ops):
l, r = sorted(int(x) for x in rng.integers(0, n + 1, size=2))
if l == r:
continue
u = rng.random()
if u < 0.25:
v = int(rng.integers(-9, 10))
st.actualizar(l, r, (1, v) if afines else v); ref[l:r] += v
elif u < 0.5 and afines:
c = int(rng.integers(-9, 10))
st.actualizar(l, r, (0, c)); ref[l:r] = c
else:
got = st.consultar(l, r)
got = got[0] if afines else got
if got != consulta_ref(ref[l:r]):
return k
return None
print("mínimo + sumar: primer fallo en la operación", prueba(min_suma, np.min))
print("suma + afín: primer fallo en la operación", prueba(suma_afin, np.sum, afines=True))
# El error típico: componer al revés (aplicar la etiqueta vieja DESPUÉS de la nueva)
al_reves = lambda f2, f1: (f1[0] * f2[0], f1[0] * f2[1] + f1[1])
print("suma + afín al revés: primer fallo en la operación", prueba(lambda v: suma_afin(v, al_reves), np.sum, afines=True))Both correct instances pass 3000 operations without failure, and reversed composition fails at operation 4. Here the error appears early because one in four operations is assignment; with few assignments the same defect can take thousands of operations to appear, which is why tests must force mixes of every update type.
The sparse table, generic in the operation, versus NumPy with four associative operations, three idempotent and one not:
def tabla_dispersa(a, op):
"""T[k][i] = op de a[i : i + 2^k]. O(n log n) entradas."""
T = [list(a)]
k = 1
while (1 << k) <= len(a):
prev, h = T[-1], 1 << (k - 1)
T.append([op(prev[i], prev[i + h]) for i in range(len(a) - (1 << k) + 1)])
k += 1
return T
def consulta_dispersa(T, op, l, r):
"""op de a[l..r] (cerrado) con dos ventanas de longitud 2^k que se solapan."""
k = (r - l + 1).bit_length() - 1
return op(T[k][l], T[k][r - (1 << k) + 1])
rng = np.random.default_rng(3)
a = rng.integers(1, 10**6, size=5000).tolist()
for nombre, op, ref in [("mín", min, np.min), ("mcd", math.gcd, np.gcd.reduce),
("OR", lambda x, y: x | y, np.bitwise_or.reduce), ("suma", lambda x, y: x + y, np.sum)]:
T = tabla_dispersa(a, op)
malas = 0
for _ in range(2000):
l, r = sorted(int(x) for x in rng.integers(0, len(a), size=2))
malas += consulta_dispersa(T, op, l, r) != ref(np.array(a[l:r + 1]))
print(f"{nombre:5s}: {sum(map(len, T))} entradas, {malas} consultas erróneas de 2000")With addition they all fail, even power-of-two lengths: the two windows then coincide and the result is doubled. The 56,822 entries for are , about eleven times the array: memory is the price of constant-time queries.
LCA both ways, on a random tree of 3000 nodes, against the naive parent-climbing algorithm. The Euler tour uses an explicit stack because a degenerate tree would exhaust Python recursion.
def arbol_aleatorio(n, rng):
padre = [-1] + [int(rng.integers(0, v)) for v in range(1, n)] # el padre de v es un nodo anterior
hijos = [[] for _ in range(n)]
for v in range(1, n):
hijos[padre[v]].append(v)
return padre, hijos
def euler(hijos, raiz=0):
"""Recorrido de Euler iterativo: secuencia E, profundidades y primera aparición."""
n = len(hijos)
prof, primera, E = [0] * n, [0] * n, []
pila = [(raiz, 0)] # (nodo, siguiente hijo por visitar)
while pila:
u, i = pila.pop()
if i == 0:
primera[u] = len(E)
E.append(u)
if i < len(hijos[u]):
pila.append((u, i + 1))
c = hijos[u][i]
prof[c] = prof[u] + 1
pila.append((c, 0))
return E, prof, primera
class LCAEuler:
def __init__(self, hijos):
self.E, self.prof, self.primera = euler(hijos)
pares = [(self.prof[u], u) for u in self.E] # el mínimo por profundidad trae consigo el nodo
self.T = tabla_dispersa(pares, min)
def __call__(self, u, v):
i, j = sorted((self.primera[u], self.primera[v]))
return consulta_dispersa(self.T, min, i, j)[1]
class LCASaltos:
"""Saltos binarios: arriba[k][v] es el antecesor 2^k niveles por encima (la raíz se apunta a sí misma)."""
def __init__(self, padre, prof):
n, self.prof = len(padre), prof
self.LOG = max(1, (n - 1).bit_length())
self.arriba = [[p if p >= 0 else 0 for p in padre]]
for k in range(1, self.LOG):
prev = self.arriba[-1]
self.arriba.append([prev[prev[v]] for v in range(n)])
def __call__(self, u, v):
if self.prof[u] < self.prof[v]:
u, v = v, u
d, k = self.prof[u] - self.prof[v], 0
while d: # sube d niveles: un salto por cada bit a 1 de d
if d & 1:
u = self.arriba[k][u]
d >>= 1; k += 1
if u == v:
return u
for k in range(self.LOG - 1, -1, -1): # sube a la vez mientras los antecesores difieran
if self.arriba[k][u] != self.arriba[k][v]:
u, v = self.arriba[k][u], self.arriba[k][v]
return self.arriba[0][u]
def lca_ingenuo(padre, u, v):
anc = set()
while u >= 0:
anc.add(u); u = padre[u]
while v not in anc:
v = padre[v]
return v
rng = np.random.default_rng(4)
padre, hijos = arbol_aleatorio(3000, rng)
lca_e = LCAEuler(hijos)
lca_s = LCASaltos(padre, lca_e.prof)
pares = [tuple(int(x) for x in rng.integers(0, 3000, size=2)) for _ in range(2000)]
assert all(lca_e(u, v) == lca_s(u, v) == lca_ingenuo(padre, u, v) for u, v in pares)
print(f"n = 3000: |E| = {len(lca_e.E)} = 2n - 1, altura {max(lca_e.prof)}")
print("2000 pares: Euler + tabla dispersa, saltos binarios e ingenuo coinciden")
dist = lambda u, v: lca_e.prof[u] + lca_e.prof[v] - 2 * lca_e.prof[lca_e(u, v)]
print("distancia media entre pares:", round(float(np.mean([dist(u, v) for u, v in pares])), 2))
assert all(abs(lca_e.prof[x] - lca_e.prof[y]) == 1 for x, y in zip(lca_e.E, lca_e.E[1:]))
print("profundidades consecutivas en E: siempre difieren en exactamente 1 (un array ±1)")Dynamic order statistics
The second lab augments a red-black tree (the CLRS version, with sentinel nil) with subtree sizes. Only insertion is implemented, as needed for a cumulative median; deletion maintains tam by subtracting 1 along the path to the removed node and applying the same two lines at every rotation.
ROJO, NEGRO = True, False
class Nodo:
__slots__ = ("clave", "izq", "der", "padre", "color", "tam")
def __init__(self, clave, nil):
self.clave, self.izq, self.der, self.padre, self.color, self.tam = clave, nil, nil, nil, ROJO, 1
class ArbolEstadisticos:
"""Rojinegro (CLRS) aumentado con tam(x) = número de nodos del subárbol de x."""
def __init__(self, mantener_tam_en_rotaciones=True):
self.nil = Nodo(None, None)
self.nil.izq = self.nil.der = self.nil.padre = self.nil
self.nil.color, self.nil.tam = NEGRO, 0
self.raiz = self.nil
self.bien = mantener_tam_en_rotaciones
def _rotar(self, x, lado):
"""lado = 'izq': y = x.der sube y x baja a su izquierda (y el simétrico)."""
otro = "der" if lado == "izq" else "izq"
y = getattr(x, otro)
setattr(x, otro, getattr(y, lado))
if getattr(y, lado) is not self.nil:
getattr(y, lado).padre = x
y.padre = x.padre
if x.padre is self.nil:
self.raiz = y
elif x is x.padre.izq:
x.padre.izq = y
else:
x.padre.der = y
setattr(y, lado, x)
x.padre = y
if self.bien: # solo cambian los subárboles de x y de y: dos líneas
y.tam = x.tam
x.tam = x.izq.tam + x.der.tam + 1
def insertar(self, clave):
z = Nodo(clave, self.nil)
y, x = self.nil, self.raiz
while x is not self.nil:
x.tam += 1 # z quedará dentro del subárbol de x
y = x
x = x.izq if clave < x.clave else x.der
z.padre = y
if y is self.nil:
self.raiz = z
elif clave < y.clave:
y.izq = z
else:
y.der = z
self._arreglar(z)
def _arreglar(self, z):
while z.padre.color == ROJO:
p, g = z.padre, z.padre.padre
lado, otro = ("izq", "der") if p is g.izq else ("der", "izq")
tio = getattr(g, otro)
if tio.color == ROJO: # caso 1: recolorear y subir
p.color = tio.color = NEGRO
g.color = ROJO
z = g
else:
if z is getattr(p, otro): # caso 2: enderezar el zigzag
z = p
self._rotar(z, lado)
z.padre.color = NEGRO # caso 3: rotar el abuelo
z.padre.padre.color = ROJO
self._rotar(z.padre.padre, otro)
self.raiz.color = NEGRO
def seleccionar(self, i):
"""La clave de rango i (desde 1): se compara i con el tamaño del subárbol izquierdo más uno."""
x = self.raiz
while True:
r = x.izq.tam + 1
if i == r:
return x.clave
x, i = (x.izq, i) if i < r else (x.der, i - r)
def rango(self, clave):
"""Número de claves estrictamente menores que la dada."""
x, r = self.raiz, 0
while x is not self.nil:
if clave <= x.clave:
x = x.izq
else:
r += x.izq.tam + 1
x = x.der
return r
def comprobar(self):
"""Verifica las propiedades rojinegras y los tamaños; devuelve la altura negra."""
def rec(x):
if x is self.nil:
return 1
assert x.tam == x.izq.tam + x.der.tam + 1, "tamaño desactualizado"
if x.color == ROJO:
assert x.izq.color == NEGRO and x.der.color == NEGRO, "rojo con hijo rojo"
hi, hd = rec(x.izq), rec(x.der)
assert hi == hd, "alturas negras distintas"
return hi + (x.color == NEGRO)
assert self.raiz.color == NEGRO
return rec(self.raiz)
def altura(self):
def h(x):
return 0 if x is self.nil else 1 + max(h(x.izq), h(x.der))
return h(self.raiz)
rng = np.random.default_rng(5)
claves = rng.permutation(20000).tolist()
arbol = ArbolEstadisticos()
for c in claves:
arbol.insertar(c)
arbol.comprobar()
orden = sorted(claves)
assert all(arbol.seleccionar(int(i) + 1) == orden[i] for i in rng.integers(0, 20000, size=2000))
assert all(arbol.rango(int(c)) == int(c) for c in rng.integers(0, 20000, size=2000))
print(f"20000 claves: altura {arbol.altura()} (cota 2 log2(n+1) = {2 * math.log2(20001):.1f}); select y rank correctos")
roto = ArbolEstadisticos(mantener_tam_en_rotaciones=False)
for c in claves[:200]:
roto.insertar(c)
orden = sorted(claves[:200])
malas = sum(roto.seleccionar(i + 1) != orden[i] for i in range(200))
print(f"sin actualizar tam en las rotaciones: {malas} de 200 selects erróneos")
try:
roto.comprobar()
except AssertionError as e:
print(" y la comprobación lo detecta:", e)And the comparison the design calls for: the moving median of a series (a random walk, like a price series) in windows of 101 values. With keys known beforehand, a Fenwick frequency tree over compressed keys performs each step with one insertion, one deletion and one -th search. The augmented red-black tree needs no prior knowledge of keys: it computes the cumulative median of observations as they arrive.
def mediana_movil(x, w):
"""Mediana inferior de cada ventana x[i - w + 1 .. i] con un Fenwick de frecuencias sobre claves comprimidas."""
valores = sorted(set(x)) # compresión: clave -> rango 1..m
pos = {v: i + 1 for i, v in enumerate(valores)}
f = Fenwick(len(valores))
out = []
for i, v in enumerate(x):
f.sumar(pos[v], 1)
if i >= w:
f.sumar(pos[x[i - w]], -1) # sale el más antiguo de la ventana
if i >= w - 1:
out.append(valores[f.kesimo((w + 1) // 2) - 1])
return out
rng = np.random.default_rng(6)
x = np.round(np.cumsum(rng.normal(size=20000)), 2).tolist()
w = 101
med = mediana_movil(x, w)
ref = np.median(np.lib.stride_tricks.sliding_window_view(np.array(x), w), axis=1)
print(f"{len(med)} ventanas de {w}: coincide con np.median en todas:", np.allclose(med, ref))
arbol = ArbolEstadisticos()
medianas = []
for i, v in enumerate(x[:5000]):
arbol.insertar(v)
medianas.append(arbol.seleccionar((i + 2) // 2)) # mediana inferior de los i + 1 vistos
ref_acum = [sorted(x[:i + 1])[(i + 2) // 2 - 1] for i in range(0, 5000, 499)]
print("mediana acumulada con el rojinegro, coincide en las 11 comprobaciones:", medianas[::499] == ref_acum)Finally, two-dimensional Barnes-Hut with 4000 bodies, compared with exact force (computed with NumPy in per body) for 100 random bodies:
class Celda:
__slots__ = ("x0", "y0", "s", "idx", "hijos", "m", "cx", "cy")
def construir(P, x0, y0, s, idx, cap=8, prof=0):
c = Celda()
c.x0, c.y0, c.s, c.idx, c.hijos = x0, y0, s, idx, None
c.m = len(idx)
if c.m:
c.cx, c.cy = P[idx, 0].mean(), P[idx, 1].mean() # el agregado: masa y centro de masas
if c.m > cap and prof < 30:
h = s / 2
der = P[idx, 0] >= x0 + h
arr = P[idx, 1] >= y0 + h
c.hijos = [construir(P, x0 + h * dx, y0 + h * dy, h, idx[(der == dx) & (arr == dy)], cap, prof + 1)
for dy in (0, 1) for dx in (0, 1)]
return c
EPS2 = 1e-4 # suavizado: evita la singularidad a distancia 0
def fuerza_bh(c, p, P, i, theta):
"""Fuerza gravitatoria 2D suavizada sobre el punto i, y número de interacciones usadas."""
if c.m == 0:
return 0.0, 0.0, 0
dentro = c.x0 <= p[0] < c.x0 + c.s and c.y0 <= p[1] < c.y0 + c.s
if c.hijos is None: # hoja: interacción directa con sus puntos
q = P[c.idx[c.idx != i]]
d = q - p
r3 = (d[:, 0] ** 2 + d[:, 1] ** 2 + EPS2) ** 1.5
return float((d[:, 0] / r3).sum()), float((d[:, 1] / r3).sum()), len(q)
dx, dy = c.cx - p[0], c.cy - p[1]
if not dentro and c.s < theta * math.hypot(dx, dy): # lejos: una sola masa en el centro de masas
r3 = (dx * dx + dy * dy + EPS2) ** 1.5
return c.m * dx / r3, c.m * dy / r3, 1
fx = fy = 0.0; k = 0
for h in c.hijos:
a, b, kk = fuerza_bh(h, p, P, i, theta)
fx += a; fy += b; k += kk
return fx, fy, k
rng = np.random.default_rng(7)
n = 4000
P = np.vstack([rng.normal([0.3, 0.6], 0.08, size=(n // 2, 2)), rng.normal([0.7, 0.3], 0.05, size=(n // 4, 2)),
rng.random((n - n // 2 - n // 4, 2))]).clip(0, 0.999)
raiz = construir(P, 0.0, 0.0, 1.0, np.arange(n))
obj = rng.choice(n, size=100, replace=False)
D = P[None, :, :] - P[obj][:, None, :]
R3 = (D[..., 0] ** 2 + D[..., 1] ** 2 + EPS2) ** 1.5
exacta = np.stack([(D[..., 0] / R3).sum(1), (D[..., 1] / R3).sum(1)], axis=1) # el término consigo mismo vale 0
for theta in (0.3, 0.5, 0.8, 1.2):
res = [fuerza_bh(raiz, P[i], P, i, theta) for i in obj]
F = np.array([(a, b) for a, b, _ in res])
err = np.linalg.norm(F - exacta, axis=1) / np.linalg.norm(exacta, axis=1)
print(f"theta = {theta}: {np.mean([k for *_, k in res]):6.0f} interacciones de media (exacto: {n - 1}), "
f"error relativo mediano {np.median(err):.1e}")With each body uses about 400 interactions instead of 3999, with median error around 1%; with , about 950 and error . If you repeat the experiment with 2000, 8000 or 16,000 bodies (changing n), mean interactions per body with barely move from 390 (the bound’s factor is not noticeable at these sizes), while exact calculation needs : that is the difference between nearly linear and quadratic total cost.
The professional version
Python’s standard library includes neither a Fenwick nor a segment tree: in pure Python they are written as above, and when performance matters one vectorizes the static case with NumPy or uses other libraries’ structures.
| Need | Tool |
|---|---|
| Prefix sums, integral image | np.cumsum (by axis), itertools.accumulate |
| Fixed-segment aggregates | np.add.reduceat, np.minimum.reduceat |
| Sliding windows | pandas.Series.rolling, numpy.lib.stride_tricks.sliding_window_view |
| Ordered set with rank and select | sortedcontainers.SortedList (blocked lists, not a tree) |
| Spatial ranges and neighbors | scipy.spatial.cKDTree, sklearn.neighbors.KDTree and BallTree |
| Barnes-Hut in t-SNE | sklearn.manifold.TSNE(method="barnes_hut", angle=0.5) |
| C++ | AtCoder Library lazy_segtree and fenwick_tree; __gnu_pbds::tree with order statistics |
import pandas as pd
from scipy.spatial import cKDTree
a = np.arange(1, 11)
print("cumsum:", np.cumsum(a))
cortes = [0, 3, 7]
print("reduceat, sumas de [0,3), [3,7), [7,10):", np.add.reduceat(a, cortes), " mínimos al revés:", np.minimum.reduceat(a[::-1], cortes))
s = pd.Series(x[:12])
print("máximo móvil de 4 (pandas):", s.rolling(4).max().tolist()[3:8])
arbol_kd = cKDTree(P)
cuenta = len(arbol_kd.query_ball_point([0.3, 0.6], r=0.05))
print("puntos a distancia < 0.05 de (0.3, 0.6):", cuenta, " fuerza bruta:", int((np.hypot(*(P - [0.3, 0.6]).T) < 0.05).sum()))AtCoder Library’s lazy_segtree has exactly the interface of our generic class (op, e, mapping, composition, id), but is iterative: it stores the tree in an array of size and traverses nodes bottom-up without recursion, making it several times faster. If you need old array versions (what was the minimum of a thousand updates ago?), a segment tree supports path copying and becomes a persistent structure with new nodes per update.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What must a partial node satisfy?
Step 1 of 3. Why does appear in ?
SegSumarMaximo(a) over a list a of integers, with methods sumar(l, r, v), which adds v to all elements at positions l..r (inclusive, zero-based), and maximo(l, r), which returns the maximum of positions l..r. Both must cost : a maximum segment tree with lazy addition tags. Tests compare against a naive version on random sequences with sizes that are not powers of two.class SegSumarMaximo:
def __init__(self, a):
self.n = len(a)
self.mx = [0] * (4 * self.n) # máximo del intervalo de cada nodo
self.tag = [0] * (4 * self.n) # suma pendiente para los hijos
# tu código: construir el árbol
def sumar(self, l, r, v):
# tu código
pass
def maximo(self, l, r):
# tu código
return 0Summary
- With an inverse and fixed data, prefix sums: per query in one or more dimensions, and the difference array for the inverse problem.
- The Fenwick tree stores in block , with . Queries remove the lowest set bit, updates add it and the -th is found by descending powers of two: all in with one array.
- A segment tree handles any monoid, commutative or not, because a query decomposes a range into nodes with at most two partial nodes per level.
- Lazy propagation defers range updates if they form a composition-closed family of monoid endomorphisms. Composition order (pending first, new second) is the most common source of errors.
- With idempotent aggregates and fixed data, a sparse table answers in after , and block decomposition reduces preprocessing to linear.
- LCA is an RMQ over Euler-tour depths, and general RMQ is an LCA in the Cartesian tree. Binary lifting is the simple alternative.
- An augmented balanced tree with fields depending only on children answers order statistics and interval overlaps with dynamic keys.
- In space, quadtrees and octrees provide adaptive subdivision, cell pruning in queries and aggregation of distant cells in Barnes-Hut.