Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add Binary Indexed Tree#44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
BattleMage0231 wants to merge1 commit intoOmkarPathak:master
base:master
Choose a base branch
Loading
fromBattleMage0231:master
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletionsBinary Indexed Tree/BinaryIndexedTree.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
class BinaryIndexedTree:
def __init__(self, arr):
self.len = 1 + len(arr)
self.tree = [0] * self.len # stores BIT
self.orig = [0] * self.len # stores original array
# build tree from values
for i in range(len(arr)):
self.update(i, arr[i])

def update(self, i, diff):
"""
Updates the value at index i by diff.
"""
i += 1 # BIT is one-indexed
self.orig[i] += diff # update original
# update BIT
while i < self.len:
self.tree[i] += diff
i += i & -i

def query(self, i):
"""
Returns the sum of arr[0..i], inclusive.
"""
i += 1 # BIT is one-indexed
ans = 0
while i != 0:
ans += self.tree[i]
i -= i & -i
return ans

def get(self, i):
"""
Get the element at position i
"""
return self.orig[i + 1]

if __name__ == '__main__':
bit = BinaryIndexedTree([4, 8, 4, 5, 6, 3, 2, 2, 8, 1])
print('Sum of arr[0..4]:', bit.query(4))
bit.update(2, -10) # decrease [2] by 10
print('Sum of arr[0..4] after updating arr[2]:', bit.query(4))
print('Value of arr[7]:', bit.get(7))

[8]ページ先頭

©2009-2025 Movatter.jp