# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
157210 | abil | Arranging Shoes (IOI19_shoes) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define fr first
#define sc second
#define pb push_back
#define mk make_pair
#define all(s) s.begin(),s.end()
//#define int long long
using namespace std;
const int N = (1e5 + 12);
const int mod = (1e9 + 7);
const int INF = (0x3f3f3f3f);
int a[N], minus[N], used[N], t[N * 4];
set<int > s[2][N];
set<int > :: iterator it;
int n;
void update(int pos, int new_val, int v = 1,int tl = 1,int tr = n){
if(tl == tr){
t[v] = new_val;
}
else{
int mid = (tl + tr) >> 1;
if(mid >= pos){
update(pos, new_val, v + v, tl, mid);
}
else{
update(pos, new_val, v + v + 1, mid + 1, tr);
}
t[v] = t[v + v] + t[v + v + 1];
}
}
int get(int l,int r, int v = 1,int tl = 1,int tr = n){
if(tl > r || tr < l){
return 0;
}
if(l <= tl && r >= tr){
return t[v];
}
int mid = (tl + tr) >> 1;
return (get(l, r, v + v, tl, mid) + get(l, r, v + v + 1, mid + 1, tr));
}
main()
{
cin >> n;
for(int i = 1;i <= n; i++){
scanf("%d", &a[i]);
if(a[i] < 0){
s[0][abs(a[i])].insert(i);
}
else{
s[1][a[i]].insert(i);
}
}
long long ans = 0, plus = 0;
for(int i = 1;i <= n; i++){
if(used[i]){
continue;
}
if(a[i] < 0){
it = s[1][abs(a[i])].begin();
s[1][abs(a[i])].erase(s[1][abs(a[i])].begin());
s[0][abs(a[i])].erase(s[0][abs(a[i])].begin());
ans += *it - i - 1;
ans -= get(i, *it);
update(i, -1);
update(*it, 1);
used[*it] = 1;
}
else{
it = s[0][a[i]].begin();
s[0][a[i]].erase(s[0][a[i]].begin());
s[1][abs(a[i])].erase(s[1][abs(a[i])].begin());
ans += *it - i;
ans -= get(i, i);
update(i, -1);
update(*it, 1);
used[*it] = 1;
}
}
cout << ans;
}
/*
6
-2 2 -2 2 -2 2
*/