forked from Jonathan-Uy/CSES-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyramid Array.cpp
More file actions
39 lines (33 loc) · 716 Bytes
/
Pyramid Array.cpp
File metadata and controls
39 lines (33 loc) · 716 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int maxN = 2e5+1;
int N, ds[maxN];
pii X[maxN];
void update(int idx){
for(int i = idx; i <= N; i += -i&i) ds[i]++;
}
int query(int idx){
int cnt = 0;
for(int i = idx; i; i -= -i&i)
cnt += ds[i];
return cnt;
}
int main(){
scanf("%d", &N);
for(int i = 0, x; i < N; i++){
scanf("%d", &x);
X[i] = {x, i+1};
}
sort(X, X+N, [](pii a, pii b){
return a.first > b.first;
});
long long ans = 0;
for(int k = 0; k < N; k++){
int idx = X[k].second;
int l = query(idx);
ans += min(l, k-l);
update(idx);
}
printf("%lld\n", ans);
}