#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=1000005;
const int inf=0x3f3f3f3f;
int id=0,ch[maxn][2],w[maxn],fa[maxn],root,n;
void rotate(int x)///重要的rotate操作
{
int y=fa[x],z=fa[y],l,r;
if (ch[y][0]==x) l=0;else l=1;r=l^1;
if (z) if (ch[z][0]==y) ch[z][0]=x;else ch[z][1]=x;
fa[x]=z;fa[y]=x;fa[ch[x][r]]=y;
ch[y][l]=ch[x][r];ch[x][r]=y;
}
void splay(int x,int k)/splay操作!!,这两点最为重要
{
int y=fa[x],z=fa[y];
while (fa[x]!=k)
{
y=fa[x];z=fa[y];
if (z!=k)
{
if ((ch[z][0]==y)^(ch[y][0]==x)) rotate(x);else rotate(y);
}
rotate(x);
}
if (k==0) root=x;//root在这里更新
}
以上一般不变
void insert(int x,int v)
{
int y;
while (true)
{
y=ch[x][v>w[x]];
if (y==0)
{
fa[++id]=x;
w[id]=v;
ch[x][v>w[x]]=id;
x=id;
break;
}
x=y;
}
splay(x);
}///还是用while来插入
int pre(int x)
{
int y=ch[x][0];
while (ch[y][1]) y=ch[y][1];
return w[y];
}
int nex(int x)
{
int y=ch[x][1];
while (ch[y][0]) y=ch[y][0];
return w[y];
}
int main()
{
scanf("%d",&n);
int t;
if (scanf("%d",&t)==-1) t=0;
memset(ch,0,sizeof(ch));
memset(w,0,sizeof(w));
memset(fa,0,sizeof(fa));
id=1;root=1;
ch[1][0]=ch[1][1]=0;fa[1]=0;
w[1]=t;
insert(root,inf);insert(root,-inf);
int ans=t;
for (int i=2;i<=n;i++)
{
if (scanf("%d",&t)==-1) t=0;
insert(root,t);
int a,b;
a=pre(root);b=nex(root);
ans+=min(t-a,b-t);
}
printf("%d",ans);
return 0;
}
#include#include#includeusing namespace std;const int maxn=1000005;const int inf=0x3f3f3f3f;int id=0,ch[maxn][2],w[maxn],fa[maxn],root,n;void rotate(int x)///重要的rotate操作{ int y=fa[x],z=fa[y],