File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-09/sol/BEESA-MANISH Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments