File tree
Expand file treeCollapse file tree1 file changed
+28
-0
lines changed data_structures/Binary Tree
Expand file treeCollapse file tree1 file changed
+28
-0
lines changed Original file line number | Diff line number | Diff line change |
---|
|
| 1 | +class FenwickTree: |
| 2 | + |
| 3 | +def __init__(self, SIZE): # create fenwick tree with size SIZE |
| 4 | +self.Size = SIZE |
| 5 | +self.ft = [0 for i in range (0,SIZE)] |
| 6 | + |
| 7 | +def update(self, i, val): # update data (adding) in index i in O(lg N) |
| 8 | +while (i < self.Size): |
| 9 | +self.ft[i] += val |
| 10 | +i += i & (-i) |
| 11 | + |
| 12 | +def query(self, i): # query cumulative data from index 0 to i in O(lg N) |
| 13 | +ret = 0 |
| 14 | +while (i > 0): |
| 15 | +ret += self.ft[i] |
| 16 | +i -= i & (-i) |
| 17 | +return ret |
| 18 | + |
| 19 | +if __name__ == '__main__': |
| 20 | +f = FenwickTree(100) |
| 21 | +f.update(1,20) |
| 22 | +f.update(4,4) |
| 23 | +print (f.query(1)) |
| 24 | +print (f.query(3)) |
| 25 | +print (f.query(4)) |
| 26 | +f.update(2,-5) |
| 27 | +print (f.query(1)) |
| 28 | +print (f.query(3)) |
You can’t perform that action at this time.
0 commit comments