Last active
February 6, 2020 23:57
-
-
Save andriybuday/27219dce9a573c158f88141b90c99bc4 to your computer and use it in GitHub Desktop.
Range Sum Segment Tree
This file contains hidden or 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
public class RangeSumSegmentTree { | |
private int n = 0; | |
private int[] tree; | |
public RangeSumSegmentTree(int[] a) { | |
n = a.length; | |
tree = new int[2*n]; | |
for(int i = 0; i < n; ++i) { | |
update(i, a[i]); | |
} | |
} | |
public void update(int i, int val) { | |
int k = n + i; | |
tree[k] = val; | |
for(k /= 2; k >= 1; k /= 2) { | |
// left is always 2k, right is 2k+1 | |
tree[k] = tree[2*k] + tree[2*k + 1]; | |
} | |
} | |
public int sum(int i, int j) { | |
i += n; | |
j += n; | |
int sum = 0; | |
while(i <= j) { | |
// odd are right children | |
if(i%2 == 1) { | |
sum += tree[i++]; | |
} | |
// even are left children | |
if(j%2 == 0) { | |
sum += tree[j--]; | |
} | |
i /= 2; | |
j /= 2; | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment