Link to tenka1 programmer contest C-align
- Given a sequence, require the maximization \ (\ sum _ {I = 2} ^ {I = n} | a_i-a _ {I-1} | \), \ (n \ Leq 10 ^ 5 \)
- Small, fresh, greedy, first put the largest first, and then consider the following four decisions in sequence:
- Minimum left, minimum right, maximum left, and maximum right.
- Each time the \ (MAX \) is obtained and the Left and Right endpoints are updated, the largest and smallest wave pattern can be obtained, and the two smallest values placed next to the maximum values will not be worse.
#include<bits/stdc++.h>#define R register int#define ll long long using namespace std;const int N=100001;int n,w[N],res[N],le,ri,z,y;ll ans;int gi(){ R x=0,k=1;char c=getchar(); while(c!=‘-‘&&(c<‘0‘||c>‘9‘))c=getchar(); if(c==‘-‘)k=-1,c=getchar(); while(c>=‘0‘&&c<=‘9‘)x=(x<<3)+(x<<1)+c-‘0‘,c=getchar(); return x*k;}int main(){ n=gi(); for(R i=1;i<=n;++i)w[i]=gi(); sort(w+1,w+n+1); le=2,ri=n,z=w[1],y=w[1]; while(le<=ri){ R p=abs(w[le]-z),q=abs(w[le]-y),a=abs(w[ri]-z),b=abs(w[ri]-y),Mx=max(max(p,q),max(a,b)); if(Mx==p)z=w[le],le++; else if(Mx==q)y=w[le],le++; else if(Mx==a)z=w[ri],ri--; else y=w[ri],ri--; ans+=Mx; } cout<<ans<<endl; return 0;}
Tenka1 programmer contest C-align