http://www.lydsy.com/JudgeOnline/problem.php?id=1588
#include<cstdio> #include<cstdlib> const int mod =1000000; const int inf = ~0u>>2; #define KT (ch[ ch[rt][1] ][0]) const int maxn = 200010; int ans; struct SplayTree { int sz[maxn]; int ch[maxn][2]; int pre[maxn]; int rt,top; inline void up(int x){ sz[x] = cnt[x] + sz[ ch[x][0] ] + sz[ ch[x][1] ]; } inline void Rotate(int x,int f){ int y=pre[x]; ch[y][!f] = ch[x][f]; pre[ ch[x][f] ] = y; pre[x] = pre[y]; if(pre[x]) ch[ pre[y] ][ ch[pre[y]][1] == y ] =x; ch[x][f] = y; pre[y] = x; up(y); } inline void Splay(int x,int goal){//将x旋转到goal的下面 while(pre[x] != goal){ if(pre[pre[x]] == goal) Rotate(x , ch[pre[x]][0] == x); else { int y=pre[x],z=pre[y]; int f = (ch[z][0]==y); if(ch[y][f] == x) Rotate(x,!f),Rotate(x,f); else Rotate(y,f),Rotate(x,f); } } up(x); if(goal==0) rt=x; } inline void RTO(int k,int goal){//将第k位数旋转到goal的下面 int x=rt; while(sz[ ch[x][0] ] != k-1) { if(k < sz[ ch[x][0] ]+1) x=ch[x][0]; else { k-=(sz[ ch[x][0] ]+1); x = ch[x][1]; } } Splay(x,goal); } inline void vist(int x){ if(x){ printf("结点%2d : 左儿子 %2d 右儿子 %2d %2d sz=%d\n",x,ch[x][0],ch[x][1],val[x],sz[x]); vist(ch[x][0]); vist(ch[x][1]); } } inline void Newnode(int &x,int c){ x=++top; ch[x][0] = ch[x][1] = pre[x] = 0; sz[x]=1; cnt[x]=1; val[x] = c; } inline void init(){ ans=0; ch[0][0]=ch[0][1]=pre[0]=sz[0]=0; rt=top=0; cnt[0]=0; Newnode(rt,-inf); Newnode(ch[rt][1],inf); pre[top]=rt; sz[rt]=2; } inline void Insert(int &x,int key,int f){ if(!x) { Newnode(x,key); pre[x]=f; Splay(x,0);//效率的保证 return ; } if(key==val[x]){ cnt[x]++; sz[x]++; Splay(x,0);//不加会超时,囧啊 return ; }else if(key<val[x]) { Insert(ch[x][0],key,x); } else { Insert(ch[x][1],key,x); } up(x); } void findpre(int x,int key,int &ans){ if(!x) return ; if(val[x] <= key){ ans=val[x]; findpre(ch[x][1],key,ans); } else findpre(ch[x][0],key,ans); } void findsucc(int x,int key,int &ans){ if(!x) return ; if(val[x]>=key) { ans=val[x]; findsucc(ch[x][0],key,ans); } else findsucc(ch[x][1],key,ans); } void solve() { int num; num=0; scanf("%d",&num); int x,y; findpre(rt,num,x); findsucc(rt,num,y); if(abs(x-num) <= abs(y-num)){ if(x!=-inf) ans+=abs(x-num); }else { if(y!=inf) ans+=abs(y-num); } Insert(rt,num,0); } int cnt[maxn]; int val[maxn]; }spt; int main() { int n; scanf("%d",&n); spt.init(); ans=0; scanf("%d",&ans); spt.Insert(spt.rt,ans,0); n--; while(n--) { spt.solve(); } printf("%d\n",ans); return 0; }