Skip to content

Commit 45ce3af

Browse files
authored
Add Day09 sol2
Implemented a solution to calculate the weakness of an army based on distinct power values using a segment tree for efficient querying and updating.
1 parent 8834de5 commit 45ce3af

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// submission: https://codeforces.com/contest/61/submission/356589066
2+
/* We have army of size n and n elements (power of army) Weakness of an army is equal
3+
to the number of triplets i, j, k such that i < j < k and
4+
ai > aj > ak where ax is the power of man standing at position x.
5+
powers of all the people in army are distinct. Find how weak the army is */
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
9+
using ll = long long;
10+
#define all(x) (x).begin(), (x).end()
11+
12+
const int MOD = 1e9 + 7; // 998244353
13+
const int bada= 1e6+5;
14+
ll a[bada], seg[4*bada];
15+
16+
void update(int ind,int low, int high,int pos){ // for updating/building the segment tree
17+
if(low==high){
18+
seg[ind]++;
19+
return;
20+
}
21+
int mid=(low+high)/2;
22+
if(pos<=mid) update(2*ind+1,low,mid,pos);
23+
else update(2*ind+2,mid+1,high,pos);
24+
seg[ind]=seg[2*ind+1]+seg[2*ind+2];
25+
}
26+
27+
int query(int ind,int low, int high, int p, int r){ //querying the segment tree
28+
if(low>=p && high<=r) return seg[ind];
29+
if(low>r || high<p) return 0;
30+
int mid=(low+high)/2;
31+
int left=query(2*ind+1,low,mid,p,r), right=query(2*ind+2,mid+1,high,p,r);
32+
return left+right;
33+
}
34+
// T.C.: O(nlogn)
35+
// S.C.: O(n)
36+
int main() {
37+
int n; cin>>n;
38+
vector<int> temp(n);
39+
for(int i=0;i<n;i++){
40+
cin>>a[i];
41+
temp[i]=a[i];
42+
}
43+
sort(all(temp));
44+
for(int i=0;i<bada;i++){ //a[i] is upto 1e9 so segment tree will be upto 4GB. So we compress the powers
45+
a[i]=lower_bound(all(temp),a[i])-temp.begin();
46+
}
47+
vector<ll> gr(n);
48+
for(int i=0;i<n;i++){
49+
gr[i]=query(0,0,n-1,a[i]+1,n-1); //constructing the greater than j vector
50+
update(0,0,n-1,a[i]);
51+
}
52+
ll weakness=0;
53+
for(int i=0;i<n;i++){
54+
ll le_i=a[i]-(i-gr[i]); //total nos. smaller than a[i] is a[i] -- as it's the sorted index
55+
//total elements smaller than a[i] on the left will be j-a[j] obviously
56+
weakness+=gr[i]*le_i;
57+
}
58+
cout<<weakness<<endl;
59+
}

0 commit comments

Comments
 (0)