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
For each position j (as middle element), count how many elements on its left are greater than a[j] and how many on its right are smaller than a[j]. Multiply these two counts - this gives triplets with j as middle. Sum this for all positions.
10
+
Use Fenwick Tree (BIT) to efficiently count elements in ranges. Since values go up to 10^9, compress them to 1..n first. Two passes: left-to-right for greater left counts, right-to-left for smaller right counts.
11
+
12
+
*/
13
+
#include<bits/stdc++.h>
14
+
usingnamespacestd;
15
+
16
+
int ft[1000005];
17
+
int n;
18
+
19
+
voidupd(int idx, int val){
20
+
for(; idx<=n; idx+=idx&-idx)
21
+
ft[idx]+=val;
22
+
}
23
+
24
+
intqry(int idx){
25
+
int ans=0;
26
+
for(; idx>0; idx-=idx&-idx)
27
+
ans+=ft[idx];
28
+
return ans;
29
+
}
30
+
31
+
intmain(){
32
+
cin>>n;
33
+
vector<int> a(n);
34
+
for(int i=0;i<n;i++) cin>>a[i];
35
+
36
+
// compress coordinates
37
+
vector<int> sorted_vals=a;
38
+
sort(sorted_vals.begin(),sorted_vals.end());
39
+
map<int,int> mp;
40
+
for(int i=0;i<n;i++){
41
+
mp[sorted_vals[i]]=i+1;
42
+
}
43
+
44
+
vector<int> compressed(n);
45
+
for(int i=0;i<n;i++){
46
+
compressed[i]=mp[a[i]];
47
+
}
48
+
49
+
vector<longlong> left_cnt(n), right_cnt(n);
50
+
51
+
// left pass
52
+
memset(ft,0,sizeof(ft));
53
+
for(int i=0;i<n;i++){
54
+
int pos=compressed[i];
55
+
left_cnt[i]=qry(n)-qry(pos);
56
+
upd(pos,1);
57
+
}
58
+
59
+
// right pass
60
+
memset(ft,0,sizeof(ft));
61
+
for(int i=n-1;i>=0;i--){
62
+
int pos=compressed[i];
63
+
right_cnt[i]=qry(pos-1);
64
+
upd(pos,1);
65
+
}
66
+
67
+
longlong ans=0;
68
+
for(int i=0;i<n;i++){
69
+
ans+=left_cnt[i]*right_cnt[i];
70
+
}
71
+
72
+
cout<<ans<<"\n";
73
+
74
+
return0;
75
+
}
76
+
77
+
//Tc =O(nlogn) per test SC = O(n)
78
+
/*
79
+
My submission : https://codeforces.com/contest/61/submission/356391525
0 commit comments