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>
using namespace std;
const int N=200005;
int tree[4*N];
int lazy[4*N];
void push(int idx)
{
tree[2*idx]+=lazy[idx];
lazy[2*idx]+=lazy[idx];
tree[2*idx+1]+=lazy[idx];
lazy[2*idx+1]+=lazy[idx];
lazy[idx]=0;
}
void update(int idx,int l,int r,int ql,int qr,int val)
{
if(ql>qr) return;
if(l==ql&&r==qr)
{
tree[idx]+=val;
lazy[idx]+=val;
}
else
{
push(idx);
int m=(l+r)/2;
update(2*idx,l,m,ql,min(qr,m),val);
update(2*idx+1,m+1,r,max(ql,m+1),qr,val);
tree[idx]=min(tree[2*idx],tree[2*idx+1]);
}
}
int query(int idx,int l,int r,int pos)
{
if(l==r) return tree[idx];
push(idx);
int m=(l+r)/2;
if(pos<=m) return query(2*idx,l,m,pos);
else return query(2*idx+1,m+1,r,pos);
}
long long count_swaps(vector<int> temp)
{
int n=temp.size()/2;
vector<int> s={0};
for(int i=0;i<2*n;i++) s.push_back(temp[i]);
for(int i=1;i<=2*n;i++) update(1,1,2*n,i,i,i);
vector<bool> vis(2*n+1,0);
queue<int> q[2*n+2]; //left: 2*i, right: 2*i+1
for(int i=1;i<=2*n;i++)
{
if(s[i]<0) q[-2*s[i]].push(i);
else q[2*s[i]+1].push(i);
}
long long res=0;
for(int o=1;o<=2*n;o++)
{
if(vis[o]) continue;
vis[o]=1;
if(s[o]<0)
{
q[-2*s[o]].pop();
int pos=q[-2*s[o]+1].front();
q[-2*s[o]+1].pop();
int one=query(1,1,2*n,o);
int two=query(1,1,2*n,pos);
vis[pos]=1;
res+=((long long)(two-(one+1)));
update(1,1,2*n,o+1,pos-1,1);
update(1,1,2*n,pos,pos,two-(one+1));
}
else
{
q[2*s[o]+1].pop();
int pos=q[2*s[o]].front();
q[2*s[o]].pop();
int one=query(1,1,2*n,o);
int two=query(1,1,2*n,pos);
vis[pos]=1;
res+=((long long)two-one);
update(1,1,2*n,o+1,pos-1,1);
update(1,1,2*n,pos,pos,two-one);
}
}
return res;
}
/*int main()
{
cout << count_swaps({2, 1, -1, -2});
return 0;
}*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |