1 #include "iostream"
2 #include "cstdio"
3 #include "cstring"
4 #include "string"
5 #include "algorithm"
6 using namespace std;
7 const int maxn=32767+10;
8 int n;
9 typedef struct{
10 int num,pos;
11 int L,R;
12 }Node;
13 Node p[maxn];
14 int b[maxn],c[maxn];
15 bool cmp(Node x,Node y){
16 return x.num<y.num;
17 }
18 int main()
19 {
20 while(cin>>n)
21 {
22 memset(p,0,sizeof(p));
23 memset(b,0,sizeof(b));
24 for(int i=1;i<=n;i++){
25 cin>>p[i].num;
26 c[i]=p[i].num;
27 p[i].pos=i;
28 }
29 sort(p+1,p+1+n,cmp);
30 for(int i=1;i<=n;i++)
31 b[p[i].pos]=i;
32 for(int i=1;i<=n;i++){
33 p[i].L=i-1;
34 p[i].R=i+1;
35 }
36 p[n].R=0;
37 int ans=c[1];
38 for(int i=n;i>1;i--){
39 int x=b[i];
40 if(p[x].L&&p[x].R){
41 ans+=min((p[x].num-p[p[x].L].num),(p[p[x].R].num-p[x].num));
42 p[p[x].L].R=p[x].R;
43 p[p[x].R].L=p[x].L;
44 }else if(!p[x].L){
45 ans+=(p[p[x].R].num-p[x].num);
46 p[p[x].R].L=0;
47 }else{
48 ans+=(p[x].num-p[p[x].L].num);
49 p[p[x].L].R=0;
50 }
51 }
52 cout<<ans<<endl;
53 }
54 return 0;
55 }