-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfenwick_tree.py
More file actions
31 lines (24 loc) · 823 Bytes
/
fenwick_tree.py
File metadata and controls
31 lines (24 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class FenwickTree:
def __init__(self, arr):
self.nums = [0] * (len(arr)+1)
self.tree = [0] * (len(arr)+1)
for i in range(len(arr)):
self.update(i,arr[i])
def update(self, index, value):
index += 1
delta = value - self.nums[index]
self.nums[index] = value
while index <= len(self.tree)-1:
self.tree[index] += delta
index += index & (-index)
def sum_of_n(self, index):
s = 0
index += 1
while index > 0:
s += self.tree[index]
index -= index & (-index)
return s
def sum_of_range(self, start, end):
# minus 1 from start since the range is (s, e) inclusive on both ends
start -= 1
return self.sum_of_n(end) - self.sum_of_n(start)