Skip to content

Commit 19f342f

Browse files
committed
added day 9 q2 solution
1 parent 31fedf6 commit 19f342f

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
3+
Submission link:
4+
5+
TC- o(n log n)
6+
SC - o(n)
7+
8+
Approach:
9+
Convert large numbers into smaller ranks so they are easy to work with.
10+
Treat each element as the middle of a triplet.
11+
Count bigger elements on the left and smaller elements on the right.
12+
Multiply these counts and sum for all positions to get the answer.
13+
*/
14+
15+
16+
17+
18+
19+
20+
21+
#include <bits/stdc++.h>
22+
using namespace std;
23+
24+
typedef long long ll;
25+
const int N = 1000005;
26+
int n;
27+
int a[N], t[N];
28+
int l_big[N], r_small[N];
29+
30+
void add(int i, int v) {
31+
for (; i <= n; i += i & -i) t[i] += v;
32+
}
33+
34+
int sum(int i) {
35+
int s = 0;
36+
for (; i > 0; i -= i & -i) s += t[i];
37+
return s;
38+
}
39+
40+
int main() {
41+
ios::sync_with_stdio(0); cin.tie(0);
42+
cin >> n;
43+
vector<int> v;
44+
for (int i = 0; i < n; i++) {
45+
cin >> a[i];
46+
v.push_back(a[i]);
47+
}
48+
sort(v.begin(), v.end());
49+
50+
for (int i = 0; i < n; i++) {
51+
int rk = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;
52+
l_big[i] = i - sum(rk);
53+
add(rk, 1);
54+
}
55+
56+
memset(t, 0, sizeof(t));
57+
58+
for (int i = n - 1; i >= 0; i--) {
59+
int rk = lower_bound(v.begin(), v.end(), a[i]) - v.begin() + 1;
60+
r_small[i] = sum(rk - 1);
61+
add(rk, 1);
62+
}
63+
64+
ll total = 0;
65+
for (int i = 0; i < n; i++) {
66+
total += (ll)l_big[i] * r_small[i];
67+
}
68+
cout << total << endl;
69+
70+
return 0;
71+
}

0 commit comments

Comments
 (0)