segment tree lan Fenwick tree (Binary Indexed Tree, BIT) loro-loro menjawab range query (contone sum over [l, r]) lan point update ing O(log n), dibanding karo O(n) kanggo naive scan utawa O(n) update kanggo prefix-sum array.
segment tree lan Fenwick tree (Binary Indexed Tree, BIT) loro-loro menjawab range query (contone sum over [l, r]) lan point update ing O(log n), dibanding karo O(n) kanggo naive scan utawa O(n) update kanggo prefix-sum array.
Array + many "sum of range [l,r]" and "update index i" calls:
naive prefix sums: query O(1) but UPDATE is O(n)
segment/Fenwick: query O(log n) AND update O(log n)
class Fenwick:
def __init__(self, n):
self.t = [0]*(n+1)
def update(self, i, delta): # O(log n)
i += 1
while i < len(self.t):
self.t[i] += delta
i += i & (-i) # jump to next responsible node
def prefix(self, i): # sum of [0..i], O(log n)
i += 1; s = 0
while i > 0:
s += self.t[i]
i -= i & (-i)
return s
def range_sum(self, l, r):
return self.prefix(r) - self.prefix(l-1)
Segment tree nyimpan aggregate saben segment array ing binary tree, ndhukung operasi apik apa (sum, min, max, gcd) lan, gawe lazy propagation, range update uga.
[0..7] sum
/ \
[0..3] [4..7]
/ \ / \
[0..1][2..3] [4..5][6..7] ... down to single elements
| Fenwick (BIT) | Segment tree | |
|---|---|---|
| Query / update | O(log n) | O(log n) |
| Spasi | O(n) | O(2n) |
| Operasi | sum (invertible) | operasi apik apa |
| Range update | luwih angel | gampang (lazy propagation) |
| Ukuran code | cilik | luwih gede |
Struktur iki bikin "update nilai, terus query aggregate over range" dadi cepet — penting kanggo competitive programming, analytics window, lan interval problem.
Nilih antarane loro iku trade-off: Fenwick tree cilik lan cepet kanggo sum, dene segment tree luwih flexible kanggo min/max/range-update workload.