Splay.
AC code:
#include <cstdio>
const int N=500001;
int n,sigma,tot;
struct splaytree
{
int val;
splaytree *Prnt,*Ch[2];
}*root,t[N];
splaytree *NIL=&t[0];
void insert(splaytree**,int,splaytree *);
int min(int,int);
int pre(splaytree*);
int suc(splaytree*);
int main()
{
root=NIL;
scanf("%d",&n);
for(int i=1;i<=n;i++){
int temp;
if(scanf("%d",&temp) == EOF) temp = 0;
insert(&root,temp,NIL);
if(root->Ch[0]==NIL&&root->Ch[1]==NIL) sigma=temp;
else if(root->Ch[0]==NIL) sigma+=suc(root)-temp;
else if(root->Ch[1]==NIL) sigma+=temp-pre(root);
else sigma+=min(temp-pre(root),suc(root)-temp);
}
printf("%d",sigma);
return 0;
}
int min(int x,int y)
{
return x<y?x:y;
}
void rotate(splaytree *x,int type)
{
splaytree *y=x->Prnt,*z=x->Prnt->Prnt;
x->Ch[type^1]->Prnt=y;
y->Ch[type]=x->Ch[type^1];
y->Prnt=x;
x->Ch[type^1]=y;
x->Prnt=z;
if(z!=NIL){
if(z->Ch[0]==y) z->Ch[0]=x;
else z->Ch[1]=x;
}
}
void splay(splaytree *x)
{
while(x->Prnt!=NIL){
splaytree *y=x->Prnt,*z=x->Prnt->Prnt;
if(z==NIL){
if(y->Ch[0]==x) rotate(x,0);
else rotate(x,1);
}
else{
if(z->Ch[0]==y&&y->Ch[0]==x){
rotate(y,0);
rotate(x,0);
}
else if(z->Ch[1]==y&&y->Ch[1]==x){
rotate(y,1);
rotate(x,1);
}
else if(z->Ch[0]==y&&y->Ch[1]==x){
rotate(x,1);
rotate(x,0);
}
else{
rotate(x,0);
rotate(x,1);
}
}
}
root=x;
}
int pre(splaytree *x)
{
splaytree *y=x->Ch[0];
while(y->Ch[1]!=NIL) y=y->Ch[1];
return y->val;
}
int suc(splaytree *x)
{
splaytree *y=x->Ch[1];
while(y->Ch[0]!=NIL) y=y->Ch[0];
return y->val;
}
void insert(splaytree **p,int key,splaytree *last_p)
{
if(*p==NIL){
*p=&t[++tot];
(*p)->val=key;
(*p)->Prnt=last_p;
(*p)->Ch[0]=(*p)->Ch[1]=NIL;
splay(*p);
return ;
}
if(key<=(*p)->val) insert(&(*p)->Ch[0],key,*p);
else insert(&(*p)->Ch[1],key,*p);
}