-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: jparisu <[email protected]>
- Loading branch information
Showing
2 changed files
with
47 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,43 @@ | ||
# Bucles [Python] | ||
# Fenwick [Python] | ||
|
||
```{contents} | ||
:local: | ||
:depth: 2 | ||
``` | ||
```py | ||
class FenwickTree: | ||
|
||
# O(N) | ||
# Create a Fenwick tree with n elements, all initialized to zero | ||
def __init__(self, size): | ||
self.size = size | ||
self.tree = [0] * (size) | ||
|
||
# O(logN) | ||
# Add delta to the element at index (index starts on 0) | ||
def update(self, index, delta): | ||
index += 1 | ||
while index <= self.size: | ||
self.tree[index - 1] += delta | ||
index += index & -index | ||
|
||
# O(logN) | ||
# Return the sum from 0 to index (no included) (index starts on 0) | ||
def query(self, index): | ||
acc = 0 | ||
while index > 0: | ||
acc += self.tree[index - 1] | ||
index -= index & -index | ||
return acc | ||
|
||
# O(logN) | ||
# Return the sum from 0 to index (included) (index starts on 0) | ||
def query_includes(self, index): | ||
acc = 0 | ||
index += 1 | ||
while index > 0: | ||
acc += self.tree[index - 1] | ||
index -= index & -index | ||
return acc | ||
|
||
```{todo} | ||
`Work In Progress` | ||
# O(logN) | ||
# Return the sum from start to end (both included) (index starts on 0) | ||
def query_range(self, start, end): | ||
return self.query_includes(end) - self.query(start) | ||
``` |