bzoj1208Splay
Splay查前驱后继
小tips:在bzoj上while(scanf)这种东西可以让程序多组数据一起跑 反正没加我就t了
#include<cstdio> #include<iostream> #include<cstdlib> #include<algorithm> #include<cmath> #include<cstring> #include<vector> #include<queue> using namespace std; const int maxn=100010; const int inf=1e9; const int mod=1000000; inline int read() { int x=0,f=1; char ch=getchar(); while(!isdigit(ch)){if(ch=='0')f=-f;ch=getchar();} while(isdigit(ch)){x=10*x+ch-'0';ch=getchar();} return x*f; } struct SplayTree { int rt,size; int son[maxn][2],f[maxn],val[maxn]; inline void Rotate(int x,int type) { int y=f[x]; son[y][!type]=son[x][type]; f[son[x][type]]=y; f[x]=f[y]; if(f[x])son[f[y]][son[f[y]][1]==y]=x; son[x][type]=y; f[y]=x; } inline void Splay(int x,int goal) { while(f[x]!=goal) { if(f[f[x]]==goal) { if(son[f[x]][0]==x) Rotate(x,1); else Rotate(x,0); } else { int y=f[x],z=f[y]; if(son[z][0]==y) { if(son[y][0]==x)Rotate(y,1),Rotate(x,1); else Rotate(x,0),Rotate(x,1); } else { if(son[y][1]==x)Rotate(y,0),Rotate(x,0); else Rotate(x,1),Rotate(x,0); } } } if(goal==0) rt=x; } inline void addnode(int fx,int &x,int a) { x=++size; f[x]=fx; val[x]=a; son[x][0]=son[x][1]=0; } inline void inittree() { size=0; addnode(0,rt,-inf); addnode(rt,son[rt][1],inf); } inline void addNode(int a) { int x=rt; while(son[x][val[x]<a]) x=son[x][val[x]<a]; addnode(x,son[x][val[x]<a],a); Splay(size,0); } inline void Delete(int a) { Splay(a,0); int tmp=son[rt][1]; while(son[tmp][0]) tmp=son[tmp][0]; Splay(tmp,rt); son[tmp][0]=son[rt][0]; f[son[rt][0]]=tmp; f[tmp]=0; rt=tmp; } inline int findnode(int a) { int x=rt; while(x) { if(val[x]==a)return x; if(val[x]>a)x=son[x][0]; else x=son[x][1]; } return 0; } inline int fx_min(int a) { int x=rt,minn=inf; while(x) { if(val[x]==a) return a; if(val[x]>a) minn=min(minn,val[x]); if(val[x]>a) x=son[x][0]; else x=son[x][1]; } return minn; } inline int fx_max(int a) { int x=rt,maxx=-inf; while(x) { if(val[x]==a) return a; if(val[x]<a) maxx=max(maxx,val[x]); if(val[x]<a) x=son[x][1]; else x=son[x][0]; } return maxx; } }Splay; int n,a,b,ans,Type[2]; int main() { while(scanf("%d",&n)!=EOF) { ans=0,Type[0]=Type[1]=0; Splay.inittree(); for(int i=1;i<=n;i++) { a=read(),b=read(); if(Type[!a]==0) { Type[a]++; Splay.addNode(b); } else { int minn=Splay.fx_min(b); int maxx=Splay.fx_max(b); ans=(ans+min(minn-b,b-maxx))%mod; if(b-maxx<=minn-b)Splay.Delete(Splay.findnode(maxx)); else Splay.Delete(Splay.findnode(minn)); Type[!a]--; } } cout<<ans%mod<<endl; } }