1 /**************************************************************
2 Problem: 1588
3 User: Doggu
4 Language: C++
5 Result: Accepted
6 Time:196 ms
7 Memory:1448 kb
8 ****************************************************************/
9
10 #include <cstdio>
11 #include <cmath>
12 #include <algorithm>
13
14 const int N = 40000;
15 struct Node {
16 int key, rd;
17 Node *ch[2];
18 int cmp(int x) {
19 if(x==key) return -1;
20 return x>key;
21 }
22 }pool[N], *tail=pool, *root=pool, *null=pool;
23
24 int rand() {
25 static int seed=1000007;
26 return seed=(int)seed*48271LL%2147483647;
27 }
28
29 Node* newnode(int x) {
30 Node *nd = tail++;
31 nd->ch[0]=nd->ch[1]=null;
32 nd->key=x;nd->rd=rand();
33 return nd;
34 }
35
36 void rotate(Node *&nd,int d) {//d=0 right(1) to left(0) d=1 left(0) to right(1)
37 Node *k=nd->ch[d^1];nd->ch[d^1]=k->ch[d];k->ch[d]=nd;nd=k;
38 }
39
40 int temp;
41 void query(Node *nd,int x) {
42 if(nd==null) temp=std::min(temp,x);
43 int d=nd->cmp(x);
44 temp=std::min(temp,std::abs(nd->key-x));
45 if(d==-1||nd->ch[d]==null) return ;
46 query(nd->ch[d],x);
47 }
48
49 void insert(Node *&nd,int x) {
50 if(nd==null) nd=newnode(x);
51 else {
52 int d=nd->cmp(x);
53 if(d==-1) return ;
54 //printf("INSERT:%d %d %d\n",nd->key,x,d);
55 insert(nd->ch[d],x);
56 if(nd->ch[d]->rd>nd->rd) rotate(nd,d^1);
57 }
58 }
59
60 /*void print(Node *nd) {
61 if(nd==null) return ;
62 print(nd->ch[0]);
63 printf("%d ",nd->key);
64 print(nd->ch[1]);
65 }*/
66
67 int main() {
68 null=newnode(0);
69 int n, x, ans = 0;
70 scanf("%d",&n);
71 for( int i = 1; i <= n; i++ ) {
72 scanf("%d",&x);
73 temp=0x3f3f3f3f;query(root,x);ans+=temp;
74 insert(root,x);
75 //printf("print:");print(root);printf("\n");
76 }
77 printf("%d",ans);
78 return 0;
79 }