-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2552.cpp
More file actions
52 lines (50 loc) · 1.35 KB
/
2552.cpp
File metadata and controls
52 lines (50 loc) · 1.35 KB
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
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;
}
int getRange(int left, int right) {
// inclusive
return getSum(right) - getSum(left - 1);
}
};
class Solution {
public:
long long countQuadruplets(vector<int>& nums) {
int n = nums.size();
BIT* bitLeft = new BIT(n + 1);
BIT* bitRight = new BIT(n + 1);
for (int i = 0; i < n; ++i) bitRight->update(nums[i], 1);
long long res = 0;
for (int k = 0; k < n; ++k) {
bitRight->update(nums[k], - 1);
for (int j = 0; j < k; ++j) {
bitLeft->update(nums[j], 1);
if (nums[k] < nums[j]) {
res += (long long)bitRight->getRange(nums[j] + 1, n) * (long long)bitLeft->getRange(1, nums[k] - 1);
}
}
for (int j = 0; j < k; ++j) bitLeft->update(nums[j], - 1);
}
return res;
}
};