-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbit.cpp
More file actions
40 lines (35 loc) · 672 Bytes
/
bit.cpp
File metadata and controls
40 lines (35 loc) · 672 Bytes
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
#include <iostream>
using namespace std;
#define LOGSZ 17
int tree[(1<<LOGSZ)+1];
int N = (1<<LOGSZ);
// add v to value at x
void set(int x, int v) {
while(x <= N) {
tree[x] += v;
x += (x & -x);
}
}
// get cumulative sum up to and including x
int get(int x) {
int res = 0;
while(x) {
res += tree[x];
x -= (x & -x);
}
return res;
}
// get largest value with cumulative sum less than or equal to x;
// for smallest, pass x-1 and add 1 to result
int getind(int x) {
int idx = 0, mask = N;
while(mask && idx < N) {
int t = idx + mask;
if(x >= tree[t]) {
idx = t;
x -= tree[t];
}
mask >>= 1;
}
return idx;
}