Skip to content

Commit f16270e

Browse files
author
Leyang Zou
committed
Add Binary Indexed Tree
1 parent a185878 commit f16270e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class BinaryIndexedTree:
2+
def __init__(self, arr):
3+
self.len = 1 + len(arr)
4+
self.tree = [0] * self.len # stores BIT
5+
self.orig = [0] * self.len # stores original array
6+
# build tree from values
7+
for i in range(len(arr)):
8+
self.update(i, arr[i])
9+
10+
def update(self, i, diff):
11+
"""
12+
Updates the value at index i by diff.
13+
"""
14+
i += 1 # BIT is one-indexed
15+
self.orig[i] += diff # update original
16+
# update BIT
17+
while i < self.len:
18+
self.tree[i] += diff
19+
i += i & -i
20+
21+
def query(self, i):
22+
"""
23+
Returns the sum of arr[0..i], inclusive.
24+
"""
25+
i += 1 # BIT is one-indexed
26+
ans = 0
27+
while i != 0:
28+
ans += self.tree[i]
29+
i -= i & -i
30+
return ans
31+
32+
def get(self, i):
33+
"""
34+
Get the element at position i
35+
"""
36+
return self.orig[i + 1]
37+
38+
if __name__ == '__main__':
39+
bit = BinaryIndexedTree([4, 8, 4, 5, 6, 3, 2, 2, 8, 1])
40+
print('Sum of arr[0..4]:', bit.query(4))
41+
bit.update(2, -10) # decrease [2] by 10
42+
print('Sum of arr[0..4] after updating arr[2]:', bit.query(4))
43+
print('Value of arr[7]:', bit.get(7))

0 commit comments

Comments
 (0)