-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyramid_array.cpp
More file actions
50 lines (39 loc) · 876 Bytes
/
Copy pathpyramid_array.cpp
File metadata and controls
50 lines (39 loc) · 876 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
40
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> arr;
void update(int idx) {
for (int i = idx; i <= n; i += (i & (-i))) {
arr[i]++;
}
}
int sum(int idx) {
int sum = 0;
for (int i = idx; i; i -= (i & (-i))) {
sum += arr[i];
}
return sum;
}
int main() {
cin >> n;
arr.resize(n + 1);
fill(arr.begin(), arr.end(), 0);
vector<pair<int,int>> ele;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
ele.push_back({x, i + 1});
}
sort(ele.begin(), ele.end(), [](pair<int,int> a, pair<int,int> b) {
return a.first > b.first;
});
long long moves = 0;
for (int i = 0; i < n; i++) {
int pos = ele[i].second;
int prev = sum(pos);
moves += min(prev, i - prev);
update(pos);
}
cout << moves << endl;
return 0;
}