splay求前驱和后继。
//#include <bits/stdc++.h>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
#define LL long long
#define inf 0x3f3f3f3f
#define MP make_pair
#define pii pair<int, int>
#define N 100010
#define M 200020
int pre[N], ch[N][2], key[N];
int tot, root;
int creat(int p, int val){
int k = ++tot;
key[k] = val;
pre[k] = p;
ch[k][0] = ch[k][1] = 0;
return k;
}
void rot(int x){
int y = pre[x], d = ch[y][1] == x;
ch[y][d] = ch[x][!d];
if(ch[x][!d]) pre[ch[x][!d]] = y;
ch[x][!d] = y;
pre[x] = pre[y];
pre[y] = x;
if(pre[x]) ch[pre[x]][ch[pre[x]][1] == y] = x;
// push_up(y);
}
void splay(int x, int goal){
while(pre[x] != goal){
int f = pre[x], ff = pre[f];
if(ff == goal)
rot(x);
else if((ch[ff][1] == f) == (ch[f][1] == x))
rot(f), rot(x);
else rot(x), rot(x);
}
if(goal == 0) root = x;
}
bool insert(int k){
if(root == 0){
root = creat(0, k);
return 1;
}
int x = root;
while(ch[x][key[x]<k]){
if(key[x] == k){
splay(x, 0);
return 0;
}
x = ch[x][key[x]<k];
}
if(key[x] == k){
splay(x, 0);
return 0;
}
ch[x][key[x]<k] = creat(x, k);
splay(ch[x][key[x]<k], 0);
return 1;
}
int find_pre(int x){
int t = ch[x][0];
if(t == 0) return -inf;
while(ch[t][1])
t = ch[t][1];
return key[t];
}
int find_suf(int x){
int t = ch[x][1];
if(t == 0) return inf;
while(ch[t][0])
t = ch[t][0];
return key[t];
}
int main(){
int n;
scanf("%d", &n);
tot = root = 0;
LL ans = 0;
while(n--){
int v;
if(scanf("%d", &v) == EOF) v = 0;
if(root == 0){
ans += v;
insert(v);
continue;
}
if(!insert(v)) continue;
int ret = min(key[root] - find_pre(root), find_suf(root) - key[root]);
ans += ret;
}
printf("%lld\n", ans);
return 0;
}