【分析】
裸题
前驱后鸡。可以用set


【代码】

//洛谷 P2234 [HNOI2002] 营业额统计
#include<iostream>
#include<cstring>
#include<cstdio>
#define inf 1e9+7
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=33000;
ll ans;
int n,m,sz,root;
int key[mxn],cnt[mxn],ch[mxn][2],f[mxn],size[mxn];
inline void clear(int x)
{
size[x]=key[x]=cnt[x]=f[x]=ch[x][0]=ch[x][1]=0;
}
inline int get(int x)
{
return ch[f[x]][0]==x?0:1;
}
inline void update(int x)
{
size[x]=size[ch[x][0]]+size[ch[x][1]]+cnt[x];
}
inline void rotate(int x)
{
int fa=f[x],fafa=f[fa],which=get(x);
ch[fa][which]=ch[x][which^1],f[ch[fa][which]]=fa;
ch[x][which^1]=fa,f[fa]=x;
f[x]=fafa;
if(fafa) ch[fafa][ch[fafa][1]==fa]=x;
update(fa),update(x);
}
inline void splay(int x,int last)
{
for(int fa;(fa=f[x])!=last;rotate(x))
if(f[fa]!=last) rotate(get(x)==get(fa)?fa:x);
if(!last) root=x;
}
inline void insert(int x)
{
if(!root)
{
root=++sz;cnt[sz]=size[sz]=1,key[sz]=x;
ch[sz][0]=ch[sz][1]=f[sz]=0;
return;
}
int now=root,fa=0;
while(1)
{
fa=now;
if(x==key[now]) {cnt[now]++;return;}
if(x<key[now]) now=ch[now][0];
else now=ch[now][1];
if(!now)
{
sz++;
key[sz]=x,cnt[sz]=size[sz]=1;
ch[sz][0]=ch[sz][1]=0,f[sz]=fa;
ch[fa][x>key[fa]]=sz;update(fa);
splay(sz,0);
return;
}
}
}
inline int pre(int x)
{
int now=root,res=-inf;
while(1)
{
if(key[now]==x) return key[now];
if(x>key[now])
{
res=max(res,key[now]);
if(ch[now][1]) now=ch[now][1];
else {splay(now,0);return res;}
}
else
{
if(ch[now][0]) now=ch[now][0];
else {splay(now,0);return res;}
}
}
}
inline int next(int x)
{
int now=root,res=inf;
while(1)
{
if(key[now]==x) return key[now];
if(x>key[now])
{
if(ch[now][1]) now=ch[now][1];
else {splay(now,0);return res;}
}
else
{
res=min(res,key[now]);
if(ch[now][0]) now=ch[now][0];
else {splay(now,0);return res;}
}
}
}
int main()
{
// freopen("turnover8.in","r",stdin);
// freopen("turnover.out","w",stdout);
int i,j,x,t1,t2;
scanf("%d%lld",&n,&ans);
insert(ans);
fo(i,2,n)
{
scanf("%d",&x);
t1=pre(x),t2=next(x);
insert(x);
ans+=min(x-t1,t2-x);
}
printf("%lld\n",ans);
return 0;
}