Fenwick Trees (Binary Indexed Trees) #
This module formalizes pure universe-polymorphic Fenwick trees (binary indexed trees,
[Fenwick1994], pp. 328–332):
- Over any
[AddCommMonoid α]: zero-initialized treeszeros, point incrementsadd(addLoop), prefix queriesprefixSum, anda.size-step immediate-parent constructionofArray(buildLoop) andofList, together with the loop invariantBuildInv. - Over any
[AddCommGroup α]: half-open range queriesrangeSum, point readsget, and point assignmentsset.
For a bounded-word Word-RAM implementation with checked instruction-count bounds (O(log n) per
update and prefix query and O(n) initialization), see
Cslib.DataStructure.FenwickTree.WordRAM.
Source Conventions #
- Indexing:
[Fenwick1994]indexes frequencies from0, using nodes1 .. n(whereV[m]holdsF[m - lowbit m + 1 .. m]) with element0held separately (V[0] = F[0], p. 328). Here a length-nsequences : List α(0-indexed positions0 .. n - 1) is shifted by1into nodesm ∈ [1, n]([Fenwick1994], "PRINCIPLES", pp. 328–329, Figure 1 on p. 328 and Figures 2–3 on p. 329), stored at0-based array slott.tree[m - 1]and aggregating((s.take m).drop (m - lowbit m)).sum. - Out-of-bounds totality:
prefixSum t lenclampslentot.size(matching(s.take len).sumfor alllen : ℕ), andadd t pos δ/set t pos vleavetunchanged whenpos ≥ t.size(matchingPrefixSums.addAt s pos δands.set pos v). - Algebraic generality and standard extensions:
[Fenwick1994]presents cumulative prefix queries (GetCumul, "THE CUMULATIVE FREQUENCY", Figure 4, p. 330) and upward point increments ("UPDATING THE TABLE", pp. 331–332, Figures 5–6 on p. 331) over integer frequencies (plus specialized single-frequency extraction in "READING A SINGLE FREQUENCY", Figure 7, p. 332). Herezeros,prefixSum,add, andofArrayrequire only[AddCommMonoid α]; immediate-parent propagationofArray/ofList(m ↦ m + lowbit m) is standard BIT folklore, andrangeSum,get, andsetare standard[AddCommGroup α]subtraction corollaries ofprefixSumandadd.
Main definitions #
Cslib.DataStructure.FenwickTree: array-backed Fenwick tree of sizet.size.Cslib.DataStructure.FenwickTree.Valid: invariant couplingttos : List α.Cslib.DataStructure.FenwickTree.zeros,buildLoop,ofArray,ofList,BuildInv: zero initialization and immediate-parent construction with its step invariant.Cslib.DataStructure.FenwickTree.prefixSum,addLoop,add: prefix queries and point increments over[AddCommMonoid α].Cslib.DataStructure.FenwickTree.rangeSum,get,set: half-open range sums, point reads, and point assignments over[AddCommGroup α].
Main results #
Cslib.DataStructure.FenwickTree.Valid.unique:Valid t suniquely determinest(so any valid construction, includingofList sand incrementaladdfromzeros, produces the exact same tree).Cslib.DataStructure.FenwickTree.prefixSum_eq:prefixSumcomputes(s.take len).sum.Cslib.DataStructure.FenwickTree.valid_add:addpreservesValidforPrefixSums.addAt s pos δ.Cslib.DataStructure.FenwickTree.valid_ofArrayandvalid_ofList:ofArrayandofListbuild valid Fenwick trees via immediate-parent propagation (BuildInv.step,BuildInv.parent_add_le_sum).Cslib.DataStructure.FenwickTree.rangeSum_eq,get_eq,valid_set: correctness of range sums, point reads, and point assignments over[AddCommGroup α].
References #
Array-backed Fenwick tree (binary indexed tree) over α.
- tree : Array α
Internal
0-indexed storage array where entrym - 1holds nodem's interval sum.
Instances For
Logical length of the represented sequence.
Fenwick tree representation invariant: t has length s.length and each 1-based node m
(1 ≤ m ≤ t.tree.size) stores the interval sum ((s.take m).drop (m - lowbit m)).sum.
Canonical representation uniqueness: Valid t s uniquely determines t.
Bridging List slice sums and Finset.Ico sums #
Zero-initialized Fenwick tree #
All-zero Fenwick tree of length n.
Downward Fenwick query loop accumulating interval sums along m, m - lowbit m, ….
Prefix sum of the first len elements ([Fenwick1994], "THE CUMULATIVE FREQUENCY", Figure 4,
p. 330). Clamps len to t.size.
Functional correctness of prefixSum ([Fenwick1994], "THE CUMULATIVE FREQUENCY", Figure 4,
p. 330): on any valid tree for s, prefixSum t len equals (s.take len).sum for all
len : ℕ.
Upward Fenwick update loop on a backing array: adds δ at 0-based slot m - 1 along
m, m + lowbit m, … ≤ n.
Add δ at 0-based index pos ([Fenwick1994], "UPDATING THE TABLE", pp. 331–332,
Figures 5–6 on p. 331). Leaves t unchanged when t.size ≤ pos.
add t pos δ preserves Valid with respect to PrefixSums.addAt s pos δ
([Fenwick1994], "UPDATING THE TABLE", pp. 331–332, Figures 5–6 on p. 331).
Immediate-parent propagation loop: for m = 1 .. n, adds tree[m - 1] into its immediate
Fenwick parent m + lowbit m when in range.
Construct a Fenwick tree from a : Array α by adding each node m once into its immediate
Fenwick parent m + lowbit m.
Construct a Fenwick tree from s : List α.
Loop invariant for immediate-parent propagation after processing nodes 1 .. m - 1.
Backing array preserves the length of
s.- done_eq (idx : ℕ) (x✝ : 1 ≤ idx) : idx < m → ∀ (x✝¹ : idx ≤ tree.size), tree[idx - 1] = ∑ i ∈ Finset.Ico (idx - lowbit idx) idx, s.getD i 0
Nodes
< malready hold their final Fenwick interval sums. - todo_eq (idx : ℕ) (x✝ : 1 ≤ idx) : m ≤ idx → ∀ (x✝¹ : idx ≤ tree.size), tree[idx - 1] = s.getD (idx - 1) 0 + ∑ c ∈ fenwickChildren idx with c < m, ∑ i ∈ Finset.Ico (c - lowbit c) c, s.getD i 0
Nodes
≥ mholds[idx - 1]plus contributions from processed immediate children.
Before the first propagation step (m = 1), a satisfies BuildInv a.toList 1.
ofArray a constructs a valid Fenwick tree representing a.toList.
Half-open range sum ((s.take r).drop l).sum over [AddCommGroup α], computed as the
difference prefixSum t r - prefixSum t l when l < r.
Point query at 0-based index pos (0 out of bounds).
Point assignment setting s[pos] := v (no-op when t.size ≤ pos).