set大法好
(颓)
//Writer : Hsz %WJMZBMR%tourist%hzwer
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cctype>
#include <vector>
#include <cstdlib>
#include <algorithm>
#define LL long long
#define M(a,b) memset(a,b,sizeof a)
using namespace std;
const int inf=0x3fffffff;
LL in()
{
LL x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9') {
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=(x<<3)+(x<<1)+ch-'0';
ch=getchar();
}
return x*f;
}
void out(int x)
{
int a[25],wei=0;
if(x<0) putchar('-'),x=-x;
for(; x; x/=10) a[++wei]=x%10;
if(wei==0) {
puts("0");
return;
}
for(int j=wei; j>=1; --j) putchar('0'+a[j]);
putchar('
');
}
int n;
LL sum,t;
set<int> s;
set<int>::iterator s1;
int main()
{
n=in();
sum=in();
s.insert(sum);
for(int i=2; i<=n; i++) {
t=in();
s1=s.lower_bound(t);
LL tp=inf;
if(s1!=s.end()) tp=min(tp,abs((*s1)-t));
if(s1!=s.begin()) tp=min(tp,abs((*--s1)-t));
sum+=tp;
s.insert(t);
}
out(sum);
return 0;
}