-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
48 lines (43 loc) · 1.03 KB
/
Solution.cpp
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
class BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
int lowbit(int x) {
return x & -x;
}
};
class Solution {
public:
long long goodTriplets(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
vector<int> pos(n);
for (int i = 0; i < n; ++i) pos[nums2[i]] = i + 1;
BinaryIndexedTree* tree = new BinaryIndexedTree(n);
long long ans = 0;
for (int& num : nums1) {
int p = pos[num];
int left = tree->query(p);
int right = n - p - (tree->query(n) - tree->query(p));
ans += 1ll * left * right;
tree->update(p, 1);
}
return ans;
}
};