forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfenwick_tree.py
247 lines (202 loc) · 6.22 KB
/
fenwick_tree.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
fromcopyimportdeepcopy
classFenwickTree:
"""
Fenwick Tree
More info: https://en.wikipedia.org/wiki/Fenwick_tree
"""
def__init__(self, arr: list[int] |None=None, size: int|None=None) ->None:
"""
Constructor for the Fenwick tree
Parameters:
arr (list): list of elements to initialize the tree with (optional)
size (int): size of the Fenwick tree (if arr is None)
"""
ifarrisNoneandsizeisnotNone:
self.size=size
self.tree= [0] *size
elifarrisnotNone:
self.init(arr)
else:
raiseValueError("Either arr or size must be specified")
definit(self, arr: list[int]) ->None:
"""
Initialize the Fenwick tree with arr in O(N)
Parameters:
arr (list): list of elements to initialize the tree with
Returns:
None
>>> a = [1, 2, 3, 4, 5]
>>> f1 = FenwickTree(a)
>>> f2 = FenwickTree(size=len(a))
>>> for index, value in enumerate(a):
... f2.add(index, value)
>>> f1.tree == f2.tree
True
"""
self.size=len(arr)
self.tree=deepcopy(arr)
foriinrange(1, self.size):
j=self.next_(i)
ifj<self.size:
self.tree[j] +=self.tree[i]
defget_array(self) ->list[int]:
"""
Get the Normal Array of the Fenwick tree in O(N)
Returns:
list: Normal Array of the Fenwick tree
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> f.get_array() == a
True
"""
arr=self.tree[:]
foriinrange(self.size-1, 0, -1):
j=self.next_(i)
ifj<self.size:
arr[j] -=arr[i]
returnarr
@staticmethod
defnext_(index: int) ->int:
returnindex+ (index& (-index))
@staticmethod
defprev(index: int) ->int:
returnindex- (index& (-index))
defadd(self, index: int, value: int) ->None:
"""
Add a value to index in O(lg N)
Parameters:
index (int): index to add value to
value (int): value to add to index
Returns:
None
>>> f = FenwickTree([1, 2, 3, 4, 5])
>>> f.add(0, 1)
>>> f.add(1, 2)
>>> f.add(2, 3)
>>> f.add(3, 4)
>>> f.add(4, 5)
>>> f.get_array()
[2, 4, 6, 8, 10]
"""
ifindex==0:
self.tree[0] +=value
return
whileindex<self.size:
self.tree[index] +=value
index=self.next_(index)
defupdate(self, index: int, value: int) ->None:
"""
Set the value of index in O(lg N)
Parameters:
index (int): index to set value to
value (int): value to set in index
Returns:
None
>>> f = FenwickTree([5, 4, 3, 2, 1])
>>> f.update(0, 1)
>>> f.update(1, 2)
>>> f.update(2, 3)
>>> f.update(3, 4)
>>> f.update(4, 5)
>>> f.get_array()
[1, 2, 3, 4, 5]
"""
self.add(index, value-self.get(index))
defprefix(self, right: int) ->int:
"""
Prefix sum of all elements in [0, right) in O(lg N)
Parameters:
right (int): right bound of the query (exclusive)
Returns:
int: sum of all elements in [0, right)
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> res = True
>>> for i in range(len(a)):
... res = res and f.prefix(i) == sum(a[:i])
>>> res
True
"""
ifright==0:
return0
result=self.tree[0]
right-=1# make right inclusive
whileright>0:
result+=self.tree[right]
right=self.prev(right)
returnresult
defquery(self, left: int, right: int) ->int:
"""
Query the sum of all elements in [left, right) in O(lg N)
Parameters:
left (int): left bound of the query (inclusive)
right (int): right bound of the query (exclusive)
Returns:
int: sum of all elements in [left, right)
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> res = True
>>> for i in range(len(a)):
... for j in range(i + 1, len(a)):
... res = res and f.query(i, j) == sum(a[i:j])
>>> res
True
"""
returnself.prefix(right) -self.prefix(left)
defget(self, index: int) ->int:
"""
Get value at index in O(lg N)
Parameters:
index (int): index to get the value
Returns:
int: Value of element at index
>>> a = [i for i in range(128)]
>>> f = FenwickTree(a)
>>> res = True
>>> for i in range(len(a)):
... res = res and f.get(i) == a[i]
>>> res
True
"""
returnself.query(index, index+1)
defrank_query(self, value: int) ->int:
"""
Find the largest index with prefix(i) <= value in O(lg N)
NOTE: Requires that all values are non-negative!
Parameters:
value (int): value to find the largest index of
Returns:
-1: if value is smaller than all elements in prefix sum
int: largest index with prefix(i) <= value
>>> f = FenwickTree([1, 2, 0, 3, 0, 5])
>>> f.rank_query(0)
-1
>>> f.rank_query(2)
0
>>> f.rank_query(1)
0
>>> f.rank_query(3)
2
>>> f.rank_query(5)
2
>>> f.rank_query(6)
4
>>> f.rank_query(11)
5
"""
value-=self.tree[0]
ifvalue<0:
return-1
j=1# Largest power of 2 <= size
whilej*2<self.size:
j*=2
i=0
whilej>0:
ifi+j<self.sizeandself.tree[i+j] <=value:
value-=self.tree[i+j]
i+=j
j//=2
returni
if__name__=="__main__":
importdoctest
doctest.testmod()