#include<bits/stdc++.h>
#define LL long long
#define INF 0x3f3f3f3f
#define MAXN 100005
using namespace std;
inline int read(){
int s=0,w=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getchar();}
return s*w;
}
const int mod=1000000;
int p,tot,bj=2;LL ans;
int size[MAXN],num[MAXN],val[MAXN],rd[MAXN];
int son[MAXN][2];
void pushup(int p){size[p]=size[son[p][0]]+size[son[p][1]]+num[p];}
void rotate(int &p,int d){
int k=son[p][d^1];
son[p][d^1]=son[k][d];
son[k][d]=p;
pushup(p);pushup(k);p=k;
return;
}
void Insert(int &p,int x){
if(!p){
p=++tot;size[p]=num[p]=1;
val[p]=x;rd[p]=rand();
return;
}
if(val[p]==x){
size[p]++;num[p]++;
return;
}
int d=(val[p]<x);Insert(son[p][d],x);
if(rd[p]<rd[son[p][d]])rotate(p,d^1);
pushup(p);return;
}
void Delete(int &p,int x){
if(!p)return;
else if(val[p]<x)Delete(son[p][1],x);
else if(val[p]>x)Delete(son[p][0],x);
else{
if(!son[p][0]&&!son[p][1]){
size[p]--;num[p]--;
if(size[p]==0)p=0;
}
else if(!son[p][0]&&son[p][1]){
rotate(p,0);
Delete(son[p][0],x);
}
else if(son[p][0]&&!son[p][1]){
rotate(p,1);
Delete(son[p][1],x);
}
else if(son[p][0]&&son[p][1]){
int d=(rd[son[p][0]]>rd[son[p][1]]);
rotate(p,d);Delete(son[p][d],x);
}
}
pushup(p);
}
int pre(int p,int x){
if(!p)return -INF;
else if(val[p]>=x)return pre(son[p][0],x);
else return max(val[p],pre(son[p][1],x));
}
int nxt(int p,int x){
if(!p)return INF;
else if(val[p]<=x)return nxt(son[p][1],x);
else return min(val[p],nxt(son[p][0],x));
}
int main(){
int n=read();
while(n--){
int opt=read(),x=read();
if(opt==0){
if(bj==0)Insert(p,x);
else if(bj==1){
LL ans1=pre(p,x),ans2=nxt(p,x);
if(ans1==-INF&&ans2==INF)continue;
else if(ans1==-INF&&ans2!=INF){
ans+=ans2-x;Delete(p,ans2);
}
else if(ans1!=-INF&&ans2==INF){
ans+=x-ans1;Delete(p,ans1);
}
else if((ans2-x)<(x-ans1))ans+=ans2-x,Delete(p,ans2);
else ans+=x-ans1,Delete(p,ans1);
}
else if(bj==2)Insert(p,x),bj=0;
if(p==0)bj=2;
}
else{
if(bj==0){
LL ans1=pre(p,x),ans2=nxt(p,x);
if(ans1==-INF&&ans2==INF)continue;
else if(ans1==-INF&&ans2!=INF){
ans+=ans2-x;Delete(p,ans2);
}
else if(ans1!=-INF&&ans2==INF){
ans+=x-ans1;Delete(p,ans1);
}
else if((ans2-x)<(x-ans1))ans+=ans2-x,Delete(p,ans2);
else ans+=x-ans1,Delete(p,ans1);
}
else if(bj==1)Insert(p,x);
else if(bj==2)Insert(p,x),bj=1;
if(p==0)bj=2;
}
ans=(ans+mod)%mod;
}
printf("%lld\n",ans);
return 0;
}
原文:https://www.cnblogs.com/PPXppx/p/10645845.html