-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path493.cpp
More file actions
64 lines (61 loc) · 1.43 KB
/
493.cpp
File metadata and controls
64 lines (61 loc) · 1.43 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
53
54
55
56
57
58
59
60
61
62
63
64
class BIT {
private:
vector<int> tree;
public:
BIT(int size) {
tree.resize(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:
int reversePairs(vector<int>& nums) {
vector<int> v = nums;
int n = nums.size();
BIT* bit = new BIT(n);
sort(v.begin(), v.end());
unordered_map<int, int> mp;
for (int i = 0; i < n; ++i) {
mp[v[i]] = i + 1;
}
int res = 0;
for (int i = n - 1; i >= 0; --i) {
int index = lower_bound(v.begin(), v.end(), nums[i] / 2.0) - v.begin();
res += bit->getSum(index);
bit->update(mp[nums[i]], 1);
}
return res;
}
};
// [1,3,2,3,1]
// => [1,1,2,3,3]
// => 1:2, 2:3, 3:5
// [1,3,2,3,1] BIT [0,0,1,0,0,0]
// ^
// [1,3,2,3,1] BIT [0,0,1,0,0,1]
// ^ ^
//
// [1,2,4,4,2]
// => [1,2,2,4,4]
// => 1:1, 2:3, 4:5
// [1,2,4,4,2] BIT [0,0,0,1,0,0]
// ^
// [1,2,4,4,2] BIT [0,0,0,1,0,1]
// ^ ^
//