-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path315.cpp
More file actions
42 lines (40 loc) · 929 Bytes
/
315.cpp
File metadata and controls
42 lines (40 loc) · 929 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
41
42
class BIT {
private:
vector<int> tree;
public:
BIT(int size) {
tree = vector<int>(size + 1, 0);
}
int lsb(int x) {
return x & (-x);
}
void update(int index, int value) {
while (index < tree.size()) {
tree[index] += value;
index += lsb(index);
}
}
int getSum(int index) {
int sum = 0;
while (index) {
sum += tree[index];
index -= lsb(index);
}
return sum;
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
int base = 10001;
BIT* bit = new BIT(base * 2 + 1);
int n = nums.size();
vector<int> res(n, 0);
for (int i = n - 1; i >= 0; i--) {
int x = nums[i];
res[i] = bit->getSum(x + base - 1);
bit->update(x + base, 1);
}
return res;
}
};