Skip to content

Commit f515ff9

Browse files
day 9 q2
1 parent 31fedf6 commit f515ff9

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

  • Problems/Data-structures/Day-09/sol/Aiyaan_Mahajan
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
DAY 8
3+
Q2 Enemy Is Weak
4+
5+
*/
6+
/*
7+
8+
9+
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+
using namespace std;
15+
16+
int ft[1000005];
17+
int n;
18+
19+
void upd(int idx, int val){
20+
for(; idx<=n; idx+=idx&-idx)
21+
ft[idx]+=val;
22+
}
23+
24+
int qry(int idx){
25+
int ans=0;
26+
for(; idx>0; idx-=idx&-idx)
27+
ans+=ft[idx];
28+
return ans;
29+
}
30+
31+
int main(){
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<long long> 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+
long long 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+
return 0;
75+
}
76+
77+
//Tc =O(nlogn) per test SC = O(n)
78+
/*
79+
My submission : https://codeforces.com/contest/61/submission/356391525
80+
*/

0 commit comments

Comments
 (0)