You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Take each element as one by one and treat that element as middle element,count number of elements greater than that element on left side of that element and count
10
+
number of elements smaller than that element on right side of that element.
11
+
12
+
Use a Fenwick Tree (Binary Indexed Tree) to efficiently count elements in ranges, Since array values can be as large as 10^9, first compress the values to ranks 1..n
13
+
14
+
Do the left to right pass in Fenwick tree to count number of elements greater than current element on left side.
15
+
16
+
Reset Fenwick tree and do right to left pass to count number of elements smaller than current element on right side.
17
+
18
+
Finally, for each element multiply the two counts and sum them up to get the final answer.
19
+
20
+
*/
21
+
22
+
#include<bits/stdc++.h>
23
+
usingnamespacestd;
24
+
25
+
typedeflonglong ll;
26
+
constint N = 1000005;
27
+
int n;
28
+
int a[N], t[N];
29
+
int l_big[N], r_small[N];
30
+
31
+
voidadd(int i, int v) {
32
+
for (; i <= n; i += i & -i) t[i] += v;
33
+
}
34
+
35
+
intsum(int i) {
36
+
int s = 0;
37
+
for (; i > 0; i -= i & -i) s += t[i];
38
+
return s;
39
+
}
40
+
41
+
intmain() {
42
+
ios::sync_with_stdio(0); cin.tie(0);
43
+
cin >> n;
44
+
vector<int> v;
45
+
for (int i = 0; i < n; i++) {
46
+
cin >> a[i];
47
+
v.push_back(a[i]);
48
+
}
49
+
sort(v.begin(), v.end());
50
+
51
+
for (int i = 0; i < n; i++) {
52
+
int rk = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;
53
+
l_big[i] = i - sum(rk);
54
+
add(rk, 1);
55
+
}
56
+
57
+
memset(t, 0, sizeof(t));
58
+
59
+
for (int i = n - 1; i >= 0; i--) {
60
+
int rk = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;
0 commit comments