题目大意:平衡树,要求插入删除找最接近的数
题解:找最接近的明显是前驱后继进行比较,由于人和宠物不会同时出现,维护一棵平衡树就好了
我的收获:sbt……
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define son(x,y) c[c[x][y]][y]
const int M=100005;
const int P=1000000;
int n,x,top;
long long ans;
int c[M][2],k[M],sz[M];
inline void pushup(int x){sz[x]=sz[c[x][0]]+sz[c[x][1]]+1;}
inline void node(int &x,int v){x=++top,c[x][0]=c[x][1]=0,sz[x]=1,k[x]=v;}
void rotate(int &x,int k){
int y=c[x][k^1];
c[x][k^1]=c[y][k];
c[y][k]=x;sz[y]=sz[x];
pushup(x);x=y;
}
void insert(int &x,int v){
if(!x) node(x,v);
else
{
sz[x]++;bool m=v>=k[x];
insert(c[x][m],v);
if(sz[son(x,m)]>sz[c[x][m^1]])
rotate(x,m^1);
}
}
void del(int &x,int v){
if(!x) return ;sz[x]--;
if(k[x]!=v) del(c[x][v>k[x]],v);
else
{
int l=c[x][0],r=c[x][1];
if(!l&&r) x=r;
else if(l&&!r) x=l;
else if(!l&&!r) x=0;
else {
while(c[r][0]) r=c[r][0];
k[x]=k[r];
del(c[x][1],k[r]);
}
}
}
int suc(int &x,int y,int v){
if(!x) return y;
if(v<k[x]) return suc(c[x][0],x,v);
return suc(c[x][1],y,v);
}
int pre(int &x,int y,int v){
if(!x) return y;
if(v>k[x]) return pre(c[x][1],x,v);
return pre(c[x][0],y,v);
}
void updata(int y)
{
int s=pre(x,-1,y),t=suc(x,-1,y),z;
if(t==-1) z=s;
else if(s==-1) z=t;
else if(y-k[s]<=k[t]-y) z=s;
else z=t;
ans=(ans+abs(y-k[z]))%P;del(x,k[z]);
}
void init()
{
x=0,top=0;
int opt,y,f=-1;
cin>>n;
while(n--){
scanf("%d%d",&opt,&y);
if(!x) f=opt,insert(x,y);
else if(f==opt) insert(x,y);
else updata(y);
}
cout<<ans<<endl;
}
int main()
{
init();
return 0;
}
244

被折叠的 条评论
为什么被折叠?



