1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include<bits/stdc++.h> #define fo(i,a,b) for(int i=a;i<=b;i++) #define fd(i,a,b) for(int i=a;i>=b;i--) using namespace std;
typedef long long LL; typedef pair<int,int> pr;
const int maxn=3e5+5; const int inf=2139062143;
int n,a[maxn];
int b[maxn],b0; void discretize() { memcpy(b,a,sizeof(a)); sort(b+1,b+1+n); b0=unique(b+1,b+1+n)-b-1; fo(i,1,n) a[i]=lower_bound(b+1,b+1+b0,a[i])-b; }
int tr[4*maxn]; void tr_xg(int k,int l,int r,int x,int z) { if (l==r) { tr[k]=z; return; } int t=k<<1, mid=(l+r)>>1; if (x<=mid) tr_xg(t,l,mid,x,z); else tr_xg(t+1,mid+1,r,x,z); tr[k]=min(tr[t],tr[t+1]); }
LL ans,organs; vector<int> Q[maxn]; int cnt[maxn]; void solve() { fo(i,1,b0) Q[i].clear(); fo(i,2,n) if (a[i-1]<a[i]) { cnt[a[i-1]]++; Q[a[i]].push_back(a[i-1]); } memset(tr,127,sizeof(tr)); fo(i,1,b0) { if (cnt[i]) tr_xg(1,1,b0,i,i); for(int x:Q[i]) { if (--cnt[x]==0) tr_xg(1,1,b0,x,inf); int lp=max(tr[1],x); if (lp<=i) ans=min(ans,organs-2ll*(b[i]-b[lp])); } } }
int main() { scanf("%d",&n); fo(i,1,n) scanf("%d",&a[i]); fo(i,2,n) ans+=abs(a[i]-a[i-1]); organs=ans; fo(i,2,n-1) ans=min(ans,organs-abs(a[i]-a[i+1])+abs(a[1]-a[i+1])); fo(i,2,n-1) ans=min(ans,organs-abs(a[i]-a[i-1])+abs(a[n]-a[i-1])); discretize(); solve(); reverse(a+1,a+1+n); solve(); printf("%lld\n",ans); }
|