注:将rotate和splay换成wiki上的标准程序后可以过,请求修改rotate和splay函数QAQ,谢谢大佬
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5;
int n,v[maxn],ans=0,root=0,son[maxn][2];
int fa[maxn];
int tot=0,cnt[maxn],size[maxn];
void pushup(int x){
size[x]=size[son[x][0]]+size[son[x][1]]+cnt[x];
}
void rotate(int x){
int yy=fa[x],zz=fa[yy];
if(x==son[yy][0] && yy==son[zz][0]){
son[yy][0]=son[x][1];
fa[son[x][1]]=yy;
son[x][1]=yy;fa[yy]=x;
son[zz][0]=x;fa[x]=zz;
}
else if(x==son[yy][0] && yy==son[zz][1]){
son[yy][0]=son[x][1];
fa[son[x][1]]=yy;
son[x][1]=yy;fa[yy]=x;
son[zz][1]=x;fa[x]=zz;
}
else if(x==son[yy][1] && yy==son[zz][0]){
son[yy][1]=son[x][0];
fa[son[x][0]]=yy;
son[x][0]=yy;fa[yy]=x;
son[zz][0]=x;fa[x]=zz;
}
else if(x==son[yy][1] && yy==son[zz][1]){
son[yy][1]=son[x][0];
fa[son[x][0]]=yy;
son[x][0]=yy;fa[yy]=x;
son[zz][1]=x;fa[x]=zz;
}
pushup(yy);pushup(x);
}
void splay(int x,int to){
while(1){
if(fa[x]==to) break;
int y=fa[x];
int z=fa[y];
if(z!=to){
if((son[y][0]==x && son[z][0]==y) || (son[y][1]==x && son[z][1]==y) ){ //一字型
rotate(y);rotate(x);
}
else{ //Z字形
rotate(x);rotate(x);
}
}
else{
rotate(x);break;
}
}
if(to==0) root=x;
}
void clear(int x){ //ok
v[x]=son[x][0]=son[x][1]=fa[x]=cnt[x]=size[x]=0;
}
void insert(int x){ //ok
if(!root){
cnt[++tot]++;
v[tot]=x;
root=tot;
pushup(tot);
return;
}
int cur=root,f=0;
while(1){
if(v[cur]==x){
cnt[cur]++;
pushup(cur);
pushup(f);
splay(cur,0);
break;
}
else if(x<v[cur]){
f=cur;cur=son[cur][0];
if(!cur){
son[f][0]=++tot;
fa[tot]=f;
cnt[tot]++;
v[tot]=x;
pushup(tot);pushup(f);
splay(tot,0);
break;
}
}
else{
f=cur;cur=son[cur][1];
if(!cur){
son[f][1]=++tot;
fa[tot]=f;
cnt[tot]++;
v[tot]=x;
pushup(tot);pushup(f);
splay(tot,0);
break;
}
}
}
}
int find(int x){
int cur=root;
while(1){
if(x==v[cur]) return cur;
else if(x<v[cur]){
cur=son[cur][0];
}
else cur=son[cur][1];
}
}
int query_pre(int x){ //返回节点编号
int p=find(x);
if(cnt[p]>1) return p;
splay(p,0);
int t=son[root][0];
if(!t) return 0;
while(son[t][1]){
t=son[t][1];
}
splay(t,0);
return t;
}
int query_nxt(int x){ //返回节点编号
int p=find(x);
if(cnt[p]>1) return p;
splay(p,0);
int t=son[root][1];
if(!t) return 0;
while(son[t][0]){
t=son[t][0];
}
splay(t,0);
return t;
}
int main(){
scanf("%d",&n);
int x;
for(int i=1;i<=n;++i){
scanf("%d",&x);
insert(x);
int ppp=query_pre(x);
int qqq=query_nxt(x);
if(ppp==0 && qqq==0){
ans+=x;
}
else if(ppp==0){
ans+=v[qqq]-x;
}
else if(qqq==0){
ans+=x-v[ppp];
}
else ans+=min(x-v[ppp],v[qqq]-x);
}
printf("%d",ans);
return 0;
}