1 #include<cstdio>
2 #include<cstdlib>
3 #include<cmath>
4 using namespace std;
5 #define maxn 33000
6 int n,share[maxn];
7 int lc[maxn],rc[maxn],father[maxn],root,ans;
8
9 inline int small(int a,int b) {if (a < b) return a; return b;}
10
11 inline void work();
12 inline void zig(int);
13 inline void zag(int);
14 inline int find(int);
15 inline void ins(int);
16 inline void splay(int);
17
18 int main()
19 {
20 freopen("1588.in","r",stdin);
21 freopen("1588.out","w",stdout);
22 scanf("%d",&n);
23 int i;
24 for (i = 1;i<=n;i++)
25 scanf("%d",share+i);
26 work();
27 printf("%d",ans);
28 fclose(stdin); fclose(stdout);
29 return 0;
30 }
31
32 inline int find(int a)
33 {
34 int ret = 1000000,now = root;
35 ret = small(abs(share[now]-a),ret);
36 now = rc[root];
37 while (now > 0)
38 {
39 if (share[now] == a)
40 return 0;
41 ret = small(abs(share[now]-a),ret);
42 if (share[now] > a)
43 now = rc[now];
44 else now = lc[now];
45 }
46 now = lc[root];
47 while (now > 0)
48 {
49 if (share[now] == a)
50 return 0;
51 ret = small(abs(share[now]-a),ret);
52 if (share[now] > a)
53 now = rc[now];
54 else now = lc[now];
55 }
56 return ret;
57 }
58
59 inline void work()
60 {
61 ans = share[1]; root = 1;
62 int i,j,k;
63 for (i = 2;i<=n;i++)
64 {
65 k = find(share[i]);
66 ans += k;
67 if (k != 0)
68 ins(i);
69 }
70 }
71
72 inline void ins(int a)
73 {
74 int last,now;
75 now = root;
76 while (now != 0)
77 {
78 last = now;
79 if (share[now] > share[a])
80 now = rc[now];
81 else now = lc[now];
82 }
83 father[a] = last;
84 if (share[a] > share[last])
85 lc[last] = a;
86 else rc[last] = a;
87 splay(a);
88 root = a;
89 }
90
91 inline void zig(int x)
92 {
93 int y = father[x];
94 father[x] = father[y];
95 if (father[y] != 0)
96 {
97 if (lc[father[y]] == y)
98 lc[father[y]] = x;
99 else rc[father[y]] = x;
100 }
101 father[y] = x;
102 lc[y] = rc[x];
103 if (rc[x] != 0)
104 father[rc[x]] = y;
105 rc[x] = y;
106 }
107
108 inline void zag(int x)
109 {
110 int y = father[x];
111 father[x] = father[y];
112 if (father[y] != 0)
113 {
114 if (lc[father[y]] == y)
115 lc[father[y]] = x;
116 else rc[father[y]] = x;
117 }
118 father[y] = x;
119 rc[y] = lc[x];
120 if (lc[x] != 0)
121 father[lc[x]] = y;
122 lc[x] = y;
123 }
124
125 inline void splay(int a)
126 {
127 while (father[a] != 0)
128 {
129 if (father[father[a]] == 0)
130 {
131 if (a == lc[father[a]])
132 zig(a);
133 else zag(a);
134 }
135 else
136 {
137 if (lc[father[father[a]]]==father[a] && lc[father[a]] == a)
138 {
139 zig(father[a]),
140 zig(a);
141 }
142 else if (lc[father[father[a]]]==father[a] && rc[father[a]] == a)
143 {
144 zag(a);
145 zig(a);
146 }
147 else if (rc[father[father[a]]]==father[a] && lc[father[a]] == a)
148 {
149 zig(a);
150 zag(a);
151 }
152 else if (rc[father[father[a]]]==father[a] && rc[father[a]] == a)
153 {
154 zag(father[a]);
155 zag(a);
156 }
157 }
158 }
159 }