Skip to content

Commit 664d27b

Browse files
authored
Merge pull request #519 from MANISH-BEESA/day9-q2
added day 9 q2 solution
2 parents 98dec78 + 5d15b2a commit 664d27b

1 file changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
3+
Submission link: https://codeforces.com/contest/61/submission/356395307
4+
5+
TC- o(n log n)
6+
SC - o(n)
7+
8+
Approach:
9+
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+
using namespace std;
24+
25+
typedef long long ll;
26+
const int N = 1000005;
27+
int n;
28+
int a[N], t[N];
29+
int l_big[N], r_small[N];
30+
31+
void add(int i, int v) {
32+
for (; i <= n; i += i & -i) t[i] += v;
33+
}
34+
35+
int sum(int i) {
36+
int s = 0;
37+
for (; i > 0; i -= i & -i) s += t[i];
38+
return s;
39+
}
40+
41+
int main() {
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;
61+
r_small[i] = sum(rk - 1);
62+
add(rk, 1);
63+
}
64+
65+
ll total = 0;
66+
for (int i = 0; i < n; i++) {
67+
total += (ll)l_big[i] * r_small[i];
68+
}
69+
cout << total << endl;
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)