forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FenwickTree.java
37 lines (31 loc) · 971 Bytes
/
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
package structures;
public class FenwickTree {
// T[i] += value
public static void add(int[] t, int i, int value) {
for (; i < t.length; i |= i + 1) t[i] += value;
}
// sum[0..i]
public static int sum(int[] t, int i) {
int res = 0;
for (; i >= 0; i = (i & (i + 1)) - 1) res += t[i];
return res;
}
///////////////////////////////////////////////////
// T[i] = max(T[i], value)
public static void set(int[] t, int i, int value) {
for (; i < t.length; i |= i + 1) t[i] = Math.max(t[i], value);
}
// max[0..i]
public static int max(int[] t, int i) {
int res = Integer.MIN_VALUE;
for (; i >= 0; i = (i & (i + 1)) - 1) res = Math.max(res, t[i]);
return res;
}
// Usage example
public static void main(String[] args) {
int[] t = new int[10];
add(t, 0, 1);
add(t, 9, -2);
System.out.println(-1 == sum(t, 9));
}
}