Skip to content

Commit c95fd1f

Browse files
authored
Merge pull request prabhupant#357 from durid17/SumSegTree
SumSegTree
2 parents c685585 + 9d3b6ba commit c95fd1f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class SumSegTree():
2+
3+
def __init__(self, n, arr = None):
4+
self._t = [0] * (4 * n)
5+
self._n = n
6+
if arr: self._build(arr, 1 , 0 , n - 1)
7+
8+
def _build(self, a, v, tl, tr):
9+
if tl == tr:
10+
self._t[v] = a[tl]
11+
else:
12+
tm = (tl + tr) // 2
13+
self._build(a, v*2, tl, tm)
14+
self._build(a, v*2+1, tm+1, tr)
15+
self._t[v] = self._t[v*2] + self._t[v*2+1]
16+
17+
def _sum_util(self, v, tl, tr, l, r):
18+
if l > r: return 0
19+
20+
if l == tl and r == tr : return self._t[v]
21+
22+
tm = (tl + tr) // 2
23+
return self._sum_util(v*2, tl, tm, l, min(r, tm)) + self._sum_util(v*2+1, tm+1, tr, max(l, tm+1), r)
24+
25+
def _update_util(self, v, tl, tr, pos, new_val):
26+
if tl == tr:
27+
self._t[v] = new_val
28+
else:
29+
tm = (tl + tr) // 2
30+
if pos <= tm: self._update_util(v*2, tl, tm, pos, new_val)
31+
else: self._update_util(v*2+1, tm+1, tr, pos, new_val)
32+
self._t[v] = self._t[v*2] + self._t[v*2+1]
33+
34+
def sum(self, l, r):
35+
return self._sum_util(1 , 0 , self._n - 1 , l , r)
36+
37+
def update(self, pos, new_val):
38+
self._update_util(1 , 0 , self._n - 1 , pos , new_val)
39+
40+
def add(self, pos, change):
41+
value = self._sum(pos , pos)
42+
self._update_util(1 , 0 , self._n - 1 , pos , value + change)

0 commit comments

Comments
 (0)