Time Limit:10000MS  Memory Limit:165536K
Total Submit:23 Accepted:11
Case Time Limit:1000MS

Description

Input

Output

Sample Input

```3
1 3 1
```

Sample Output

`4`

Hint

code：

``` #include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#define maxn 500005
#define lowbit(x) ((x)&(-(x)))
#define inf 4557430888798830399LL
using namespace std;
typedef long long int64;
char ch;
int n,tot,h[maxn],pos[maxn];
int64 sum[maxn],f[maxn],ans;
struct DATA{
int val,num;
}list[maxn];
bool cmp(DATA a,DATA b){return a.val<b.val;}
struct bit{
int64 val[maxn];
void init(){memset(val,,sizeof(val));}
void insert(int x,int64 v){for (;x<=tot;x+=lowbit(x)) val[x]=min(val[x],v);}
int64 query(int x){
int64 ans=inf;
for (;x;x-=lowbit(x)) ans=min(ans,val[x]);
return ans;
}
}T1,T2;
bool ok;
for (ok=,ch=getchar();!isdigit(ch);ch=getchar()) if (ch=='-') ok=;
for (x=;isdigit(ch);x=x*+ch-'',ch=getchar());
if (ok) x=-x;
}
int main(){
for (int i=;i<=n;i++) sum[i]=sum[i-]+abs(h[i]-h[i-]);
for (int i=;i<=n;i++) list[i]=(DATA){h[i],i};
sort(list+,list+n+,cmp);
pos[]=tot=;
for (int i=;i<=n;i++){
if (list[i].val!=list[i-].val) tot++;
pos[list[i].num]=tot;
}
T1.init(),T2.init();
memset(f,,sizeof(f));
f[]=,T1.insert(pos[],f[]-sum[]-h[]),T2.insert(tot-pos[]+,f[]-sum[]+h[]);
for (int i=;i<=n;i++){
f[i]=sum[i-]+min(h[i]+T1.query(pos[i]),-h[i]+T2.query(tot-pos[i]));
T1.insert(pos[i-],f[i]-sum[i]-h[i-]);
T2.insert(tot-pos[i-]+,f[i]-sum[i]+h[i-]);
}
ans=inf;
for (int i=;i<=n;i++) ans=min(ans,f[i]+sum[n]-sum[i]);
printf("%I64d\n",ans);
return ;
}```