# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1032071 | Kipras | Arranging Shoes (IOI19_shoes) | C++17 | 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>
typedef long long ll;
using namespace std;
const ll maxN = 1e5+10;
ll n;
ll val[maxN*2], l[maxN], r[maxN], lazy[maxN], sz[maxN];
deque<ll> pos[maxN], neg[maxN];
ll used[maxN]={0};
ll ind = 0;
void build(ll v){
if(v>=n){
l[v]=ind;
r[v]=ind;
ind++;
val[v]=0;
lazy[v]=0;
sz[v]=1;
}else{
build(v*2);
build(v*2+1);
l[v]=l[v*2];
r[v]=r[v*2+1];
val[v]=0;
lazy[v]=0;
sz[v]=sz[v*2]+sz[v*2+1];
}
}
void update(ll v, ll L, ll R, ll x){
if(L>r[v]||R<l[v]){
//cout<<"ending: "<<l[v]<<" "<<r[v]<<" "<<L<<" "<<R<<" "<<v<<"\n";
return;
}
else if(L<=l[v]&&r[v]<=R){
lazy[v]+=x;
//cout<<"updation: "<<l[v]<<" "<<r[v]<<" "<<v<<"\n";
}else{
update(v*2, L, R, x);
update(v*2+1, L, R, x);
}
}
ll query(ll v, ll L, ll R){
if(L>r[v]||R<l[v]){
return 0;
}
else if(L<=l[v]&&r[v]<=R){
val[v]+=lazy[v];
lazy[v]=0;
return val[v];
}else{
if(v>=n){
val[v]+=lazy[v];
}else{
lazy[v*2]+=lazy[v];
lazy[v*2+1]+=lazy[v];
}
lazy[v]=0;
return query(v*2, L, R)+query(v*2+1, L, R);
}
}
ll count_swaps(vector<int> s){
n = s.size();
build(1);
ll rez = 0;
for(int i = 0; i < n; i++){
if(s[i]>0)
pos[s[i]].push_back(i);
else
neg[abs(s[i])].push_back(i);
}
for(int i = 0; i < n; i++){
if(used[i])continue;
ll v=abs(s[i]);
if(s[i]>0){
rez++;
pos[v].pop_front();
ll u = neg[v].front();
neg[v].pop_front();
ll p1 = i + query(1, i, i);
ll p2 = u + query(1, u, u);
update(1, 1, p2-1, 1);
//cout<<rez<<" "<<i<<" "<<u<<" "<<p1<<" "<<p2<<" a\n";
rez+=p2-p1-1;
//cout<<rez<<"a\n";
used[u]=1;
}else{
neg[v].pop_front();
ll u = pos[v].front();
pos[v].pop_front();
ll p1 = i + query(1, i, i);
ll p2 = u + query(1, u, u);
update(1, 1, p2-1, 1);
//cout<<rez<<" "<<i<<" "<<u<<" "<<p1<<" "<<p2<<" b\n";
rez+=p2-p1-1;
//cout<<rez<<"b\n";
used[u]=1;
}
}
return rez;
}
int main(){
ll m;
cin>>m;
vector<int> aa;
for(int i = 0; i < m; i++){
ll aaa;
cin>>aaa;
aa.push_back(aaa);
}
cout<<count_swaps(aa);
}