题意:中文
思路:练习splay,没什么好说的,模版参考kuangbin大神
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3fll;
const int maxn=100010;
int pre[maxn],ch[maxn][2],key[maxn];
int root,tot1;
void init(){
root=tot1=0;
ch[root][0]=ch[root][1]=key[root]=pre[root]=0;
}
void newnode(int &r,int fa,int k){
r=++tot1;
pre[r]=fa;
ch[r][0]=ch[r][1]=0;
key[r]=k;
}
void Rotate(int x,int kind){
int y=pre[x];
ch[y][!kind]=ch[x][kind];
pre[ch[x][kind]]=y;
if(pre[y]) ch[pre[y]][ch[pre[y]][1]==y]=x;
pre[x]=pre[y];
ch[x][kind]=y;
pre[y]=x;
}
void splay(int r,int goal){
while(pre[r]!=goal){
if(pre[pre[r]]==goal) Rotate(r,ch[pre[r]][0]==r);
else{
int y=pre[r];
int kind=ch[pre[y]][0]==y;
if(ch[y][kind]==r){
Rotate(r,!kind);
Rotate(r,kind);
}else{
Rotate(y,kind);
Rotate(r,kind);
}
}
}
if(goal==0) root=r;
}
void Insert(int k){
int r=root;
if(r==0){
newnode(root,0,k);
return ;
}
while(ch[r][key[r]<k]) r=ch[r][key[r]<k];
newnode(ch[r][key[r]<k],r,k);
splay(ch[r][key[r]<k],0);
}
int get_min(int r){
while(ch[r][0]) r=ch[r][0];
return r;
}
int get_max(int r){
while(ch[r][1]) r=ch[r][1];
return r;
}
int main(){
int n,a;
while(scanf("%d",&n)!=-1){
int ans=0;
init();
for(int i=0;i<n;i++){
scanf("%d",&a);
Insert(a);
if(i==0) ans+=a;
else{
int tmp=inf;
if(ch[root][0]) tmp=min(tmp,key[root]-key[get_max(ch[root][0])]);
if(ch[root][1]) tmp=min(tmp,key[get_min(ch[root][1])]-key[root]);
ans+=tmp;
}
}
printf("%d\n",ans);
}
return 0;
}