-
Notifications
You must be signed in to change notification settings - Fork 505
/
FenwickTree.java
83 lines (59 loc) · 1.54 KB
/
FenwickTree.java
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
package modern.challenge;
import java.util.Arrays;
public class FenwickTree {
private final int n;
private long[] tree;
public FenwickTree(int n) {
this.n = n;
this.tree = new long[n + 1];
}
public FenwickTree(long[] values) {
if (values == null) {
throw new IllegalArgumentException("Values array cannot be null");
}
values[0] = 0L;
this.n = values.length;
tree = values.clone();
for (int i = 1; i < n; i++) {
int parent = i + lsb(i);
if (parent < n) {
tree[parent] += tree[i];
}
}
}
public long sum(int left, int right) {
if (right < left) {
throw new IllegalArgumentException("Right should be greater or equal to left");
}
return prefixSum(right) - prefixSum(left - 1);
}
public long get(int i) {
return sum(i, i);
}
public void add(int i, long v) {
while (i < n) {
tree[i] += v;
i += lsb(i);
}
}
public void set(int i, long v) {
add(i, v - sum(i, i));
}
@Override
public String toString() {
return Arrays.toString(tree);
}
private long prefixSum(int i) {
long sum = 0L;
while (i != 0) {
sum += tree[i];
i &= ~lsb(i); // or, i -= lsb(i);
}
return sum;
}
private static int lsb(int i) {
return i & -i;
// or
// return Integer.lowestOneBit(i);
}
}