-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBIT.java
69 lines (55 loc) · 1.1 KB
/
BIT.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
public class BIT {
int []tree;
int size;
BIT(int n) {
size = n;
tree = new int[n+1];
}
int getBitmask() {
int count, i;
for(i = size, count = 0; i > 0; i >>= 1, count++);
return 1<<count;
}
int query(int i) {
int result = 0;
for(; i > 0; i -= (i&-i))
result += tree[i];
return result;
}
int query(int i, int j) {
return query(j) - (i == 1 ? 0 : query(i - 1));
}
int readSingle(int i) {
int result = tree[i];
if (i > 0) {
int lca = i - (i&-i);
i--;
while( lca != i) {
result -= tree[i];
i -= (i&-i);
}
}
return result;
}
void update(int i, int value) {
for(; i <= size; i += (i&-i))
tree[i] += value;
}
//only non-negative frequencies
//if in tree exists more than one index with a same cumFre, it returns the greatest one
int find(int cumFre) {
int index = 0,
bitMask = getBitmask();
while((bitMask != 0) && (index < size)) {
int tmp = index + bitMask;
if (cumFre >= tree[tmp]) {
index = tmp;
cumFre -= tree[index];
}
bitMask >>= 1;
}
if (cumFre != 0)
index = -1;
return index;
}
}