1 #include<cstdio>
  2 #include<algorithm>
  3 #include<cstring>
  4 #define inf 1<<29
  5 #define maxn 50000
  6 int cnt,flag,n,root,ret,ansx;
  7 using namespace std;
  8 struct treap{
  9     int lc,rc,key,pri,siz,val;
 10 }a[maxn];
 11 void pushup(int o)
 12 {
 13     a[o].siz=a[a[o].lc].siz+a[a[o].rc].siz+a[o].val;
 14 }
 15 void lturn(int &o)
 16 {
 17     int t=a[o].rc;
 18     a[o].rc=a[t].lc;
 19     a[t].lc=o;
 20     a[t].siz=a[o].siz;
 21     pushup(o);
 22     o=t;
 23     return ;
 24 }
 25 void rturn(int &o)
 26 {
 27     int t=a[o].lc;
 28     a[o].lc=a[t].rc;
 29     a[t].rc=o;
 30     a[t].siz=a[o].siz;
 31     pushup(o);
 32     o=t;
 33     return ;
 34 }
 35 void insert(int &o,int x)
 36 {
 37     if(!o)
 38     {
 39         o=++cnt;
 40         a[o]=(treap){0,0,x,rand(),1,1};
 41         return ;
 42     }
 43     a[o].siz++;
 44     if(a[o].key==x)a[o].val++;
 45     else if(a[o].key>x) 
 46     {
 47         insert(a[o].lc,x);
 48         if(a[a[o].lc].pri>a[o].pri)rturn(o);
 49     }
 50     else 
 51     {
 52         insert(a[o].rc,x);
 53         if(a[a[o].rc].pri>a[o].pri)lturn(o);
 54     }
 55 }
 56 void que_pro(int o,int x)
 57 {
 58     if(!o)return ;
 59     if(a[o].key==x)
 60     {
 61         ret=a[o].key;
 62         return ;
 63     }
 64     if(a[o].key>x)que_pro(a[o].lc,x);
 65     else
 66     {
 67         ret=a[o].key;
 68         que_pro(a[o].rc,x);
 69     }
 70     return ;
 71 }
 72 void que_sub(int o,int x)
 73 {
 74     if(!o)return ;
 75     if(a[o].key==x)
 76     {
 77         ret=a[o].key;
 78         return ;
 79     }
 80     if(a[o].key<x)que_sub(a[o].rc,x);
 81     else
 82     {
 83         ret=a[o].key;
 84         que_sub(a[o].lc,x);
 85     }
 86     return ;
 87 }
 88 void work(int x)
 89 {
 90     int ans=inf;
 91     ret=-inf;
 92     que_pro(root,x);
 93     ans=min(ans,abs(x-ret));
 94     ret=inf;
 95     que_sub(root,x);
 96     ans=min(ans,abs(x-ret));
 97     ansx+=ans;
 98     return ;
 99 }
100 int main()
101 {
102     int k;
103     scanf("%d",&n);
104     scanf("%d",&k);
105     srand(n);
106     ansx=k;
107     insert(root,k);
108     for(int i=1 ; i<n ; ++i)
109     {
110         scanf("%d",&k);
111         work(k);insert(root,k);
112     }
113     printf("%d",ansx);
114     return 0;
115 }