1 #include<bits/stdc++.h>
2 using namespace std;
3 const int N=40010;
4 int fa[N],ch[N][2],root,k[N],ind=1;
5 void zig(int x) {
6 int y=fa[x],z=fa[y];
7 fa[y]=x;
8 fa[x]=z;
9 ch[y][0]=ch[x][1],fa[ch[x][1]]=y,ch[x][1]=y;
10 if (y==ch[z][0]) ch[z][0]=x;
11 else ch[z][1]=x;
12 //size[y]=size[ch[y][0]]+size[ch[y][1]]+1;
13 }
14 void zag(int x) {
15 int y=fa[x],z=fa[y];
16 fa[y]=x,fa[x]=z;
17 ch[y][1]=ch[x][0],fa[ch[x][0]]=y,ch[x][0]=y;
18 if (y==ch[z][0]) ch[z][0]=x;
19 else ch[z][1]=x;
20 //size[y]=size[ch[y][0]]+size[ch[y][1]]+1;
21 }
22 void splay(int x,int s) {
23 while (fa[x]!=s) {
24 int y=fa[x],z=fa[y];
25 if (z==s) {
26 if (x==ch[y][0]) zig(x);
27 else zag(x);
28 break;
29 }
30 if (y==ch[z][0]) {
31 if (x==ch[y][0]) zig(y),zig(x);
32 else zag(x),zig(x);
33 }
34 else {
35 if (x==ch[y][1]) zag(y),zag(x);
36 else zig(x),zag(x);
37 }
38 }
39 //size[x]=size[ch[x][0]]+size[ch[x][1]]+1;
40 if (s==0) root=x;
41 }
42 inline void newnode(int &x,int fax,int key) {
43 x=++ind;
44 ch[x][0]=ch[x][1]=0;
45 fa[x]=fax;
46 k[x]=key;
47 }
48 inline int search(int w) {
49 int p,x=root;
50 while(x) {
51 p=x;
52 if(k[x]>w) x=ch[x][0];
53 else x=ch[x][1];
54 }
55 return p;
56 }
57 inline void ins(int w){
58 if (root==0) {
59 newnode(root,0,w);
60 return ;
61 }
62 int i=search(w);
63 if(w<k[i]) newnode(ch[i][0],i,w);
64 else newnode(ch[i][1],i,w);
65 splay(ind,0);
66 }
67 inline int pre(int x) {
68 int tmp=ch[x][0];
69 while(ch[tmp][1]) tmp=ch[tmp][1];
70 return k[tmp];
71 }
72 inline int suc(int x) {
73 int tmp=ch[x][1];
74 while(ch[tmp][0]) tmp=ch[tmp][0];
75 return k[tmp];
76 }
77 int main() {
78 int n,t,ans=0;
79 scanf("%d%d",&n,&t);
80 root=1;k[root]=t;
81 ch[root][0]=ch[root][1]=0;
82 fa[root]=0;//printf("hhh");
83 ans=t;ins(2100000);
84 ins(-2100000);
85 for (int i=2;i<=n;++i) {
86 if(scanf("%d",&t)==EOF) t=0;
87 ins(t);
88 int a=pre(root),b=suc(root);
89 ans+=min(t-a,b-t);
90 }
91 printf("%d\n",ans);
92 return 0;
93 }