1 var
2 i,j,k,l,m,n,mt,head:longint;
3 a,lef,rig,fix:array[0..1000000] of longint;
4 function min(x,y:longint):longint;inline;
5 begin
6 if x<y then min:=x else miN:=y;
7 end;
8 procedure rt(var x:longint);inline;
9 var f,l:longint;
10 begin
11 if (x=0) or (lef[x]=0) then exit;
12 f:=x;l:=lef[x];
13 lef[x]:=rig[l];
14 rig[l]:=x;
15 x:=l
16 end;
17 procedure lt(var x:longint);inline;
18 var f,r:longint;
19 begin
20 if (x=0) or (rig[x]=0) then exit;
21 f:=x;r:=rig[x];
22 rig[x]:=lef[r];
23 lef[r]:=x;
24 x:=r;
25 end;
26 procedure ins(var x,y:longint);inline;
27 begin
28 if x=0 then exit;
29 if a[y]<a[x] then
30 begin
31 mt:=min(mt,abs(a[x]-a[y]));
32 if lef[x]=0 then lef[x]:=y else ins(lef[x],y);
33 if fix[lef[x]]>fix[x] then rt(x);
34 end
35 else
36 begin
37 mt:=min(mt,abs(a[x]-a[y]));
38 if rig[x]=0 then rig[x]:=y else ins(rig[x],y);
39 if fix[rig[x]]>fix[x] then lt(x);
40 end;
41 end;
42 begin
43 readln(n);
44 randomize;
45 fillchar(lef,sizeof(lef),0);
46 fillchar(rig,sizeof(rig),0);
47 for i:=1 to n do
48 begin
49 read(a[i]);
50 fix[i]:=random(maxlongint);
51 end;
52 head:=1;
53 l:=a[1];
54 for i:=2 to n do
55 begin
56 mt:=maxlongint;j:=i;
57 ins(head,j);
58 l:=l+mt;
59 end;
60 writeln(l);
61 end.
62