Sub topic 8
The iterative bottom-up segment tree
This chapter assumes you have read the recursive segment tree chapters. You should know that a node covers a segment, that a parent combines its two children, and that a query takes O(log n) time. You should also be comfortable with >>, &, and << on integers.
Why a second implementation
The recursive tree allocates 4 * n cells and makes many function calls. The bottom-up version uses a flat array of exactly 2 * n cells and only loops. It is shorter and usually faster, so it is common in contests and performance-sensitive code.
The layout
The leaves go at the end of the array, in positions n to 2n - 1. Element a[i] lives at t[n + i]. Each internal node i is the sum of its children 2i and 2i + 1. Index 0 is never used.
The parent of node i is i >> 1. This is why no lo, hi, or node arguments are needed. The position in the array tells you everything.
The code
class IterativeSegmentTree:
# Bottom-up sum tree; leaves live at t[n..2n-1]; queries use half-open [l, r).
def __init__(self, a):
self.n = len(a)
self.t = [0] * self.n + list(a)
for i in range(self.n - 1, 0, -1):
self.t[i] = self.t[2 * i] + self.t[2 * i + 1]
def update(self, i, value):
i += self.n
self.t[i] = value
i >>= 1
while i >= 1:
self.t[i] = self.t[2 * i] + self.t[2 * i + 1]
i >>= 1
def query(self, l, r):
res = 0
l += self.n
r += self.n
while l < r:
if l & 1:
res += self.t[l]
l += 1
if r & 1:
r -= 1
res += self.t[r]
l >>= 1
r >>= 1
return res
st = IterativeSegmentTree([5, 2, 7, 1, 3])
print(st.query(1, 4)) # 2 + 7 + 1 = 10
st.update(2, 10)
print(st.query(1, 4)) # 13How the query works
The query uses a half-open range [l, r). This differs from the inclusive bounds in the recursive version. Both ends start at leaf level and climb together:
- If
lis odd, it is a right child. Its parent would include an element left of the range, so the loop takest[l]alone and moveslright by one. - If
ris odd, thenr - 1is a left child whose parent would reach past the range. The loop movesrleft by one and takest[r]. - Both indices then halve, which moves them up one level.
The loop ends when l >= r. Each level adds at most two nodes, so a query takes O(log n).
Trace query(1, 4) on the example. The leaf indices are l = 6 and r = 9. Because r is odd, it takes t[8] (the value 1). At the next level l = 3 is odd, so it takes t[3], which is 2 + 7 = 9. The total is 10.
The update
An update writes the leaf, then walks up with i >>= 1 and recomputes each ancestor from its two children. This takes O(log n) and needs no recursion.
Common errors
- Passing inclusive bounds.
query(1, 3)would missa[3]. Passr + 1or use half-open ranges throughout. - Forgetting to add
nto the index inupdate. - Starting
reswith the wrong identity. For sum it is 0, for minimum it is infinity.
Exercise
In the tree built from [5, 2, 7, 1, 3], what does self.t[1] hold after the build, and which leaf index does a[4] occupy?
Show answer
Here n = 5, so a[4] is at index 5 + 4 = 9. For this array, t[1] = t[2] + t[3] = 9 + 9 = 18, which is the sum of all five elements.