1 #include<cstdio>
2 #include<cstdlib>
3 #include<cmath>
4 #include<cstring>
5 #include<algorithm>
6 #include<iostream>
7 #include<vector>
8 #include<map>
9 #include<set>
10 #include<queue>
11 #include<string>
12 #define inf 0x3f3f3f3f
13 #define maxn 100005
14 #define maxm 100005
15 #define eps 1e-10
16 #define ll long long
17 #define for0(i,n) for(int i=0;i<=(n);i++)
18 #define for1(i,n) for(int i=1;i<=(n);i++)
19 #define for2(i,x,y) for(int i=(x);i<=(y);i++)
20 #define for3(i,x,y) for(int i=(x);i>=(y);i--)
21 #define for4(i,x) for(int i=head[(x)],y=e[i].go;i;i=e[i].next,y=e[i].go)
22 #define mod 1000000007
23 using namespace std;
24 int fa[maxn],c[maxn][2],n,k,a[maxn],tot=0,rt=0,v[maxn],sum[maxn],s[maxn];
25 int read(){
26 int x=0,f=1;char ch=getchar();
27 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
28 while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
29 return x*f;
30 }
31 void pushup(int x)
32 {
33 int l=c[x][0],r=c[x][1];
34 s[x]=s[l]+s[r]+1;
35 sum[x]=sum[l]+sum[r]+v[x];
36 }
37 void rotate(int x,int &k)
38 {
39 int y=fa[x],z=fa[y],l=c[y][1]==x,r=l^1;
40 if(y==k)k=x;else c[z][c[z][1]==y]=x;
41 fa[x]=z;fa[y]=x;fa[c[x][r]]=y;
42 c[y][l]=c[x][r];c[x][r]=y;
43 pushup(y);pushup(x);
44 }
45 void splay(int x,int &k)
46 {
47 while(x!=k)
48 {
49 int y=fa[x],z=fa[y];
50 if(y!=k)
51 {
52 if(c[z][0]==y^c[y][0]==x)rotate(x,k);else rotate(y,k);
53 }
54 rotate(x,k);
55 }
56 }
57 void ins(int &k,int kk,int x)
58 {
59 if(!k)
60 {
61 k=++tot;s[tot]=1;fa[tot]=kk;v[tot]=sum[tot]=x;return;
62 }
63 s[k]++;
64 if(x<=v[k])ins(c[k][0],k,x);else ins(c[k][1],k,x);
65 pushup(k);
66 }
67 int find(int k,int x)
68 {
69 int l=c[k][0],r=c[k][1];
70 if(s[l]+1==x)return k;
71 else if(s[l]>=x)return find(l,x);
72 else return find(r,x-s[l]-1);
73 }
74 int mi(int k,int x){
75 int i=c[k][0],j=0,tmp=inf;
76 while(i!=0){if(abs(v[i]-x)<tmp){tmp=abs(v[i]-x);j=i;}i=c[i][1];}
77 i=c[k][1];
78 while(i!=0){if(abs(v[i]-x)<tmp){tmp=abs(v[i]-x);j=i;}i=c[i][0];}
79 splay(j,rt);
80 return tmp;
81 }
82 int main(){
83 //freopen("input.txt","r",stdin);
84 //freopen("output.txt","w",stdout);
85 n=read();
86 int ans=0;
87 for1(i,n){
88 int x;if(scanf("%d",&x)==EOF)x=0;
89 ins(rt,i,x);
90 splay(i,rt);
91 if(i!=1)ans+=mi(rt,x);
92 else ans=x;
93 }
94 printf("%d",ans);
95 return 0;
96 }