其他分享
首页 > 其他分享> > D. Maximum Sum on Even Positions(翻转1次,求最大偶数位和)

D. Maximum Sum on Even Positions(翻转1次,求最大偶数位和)

作者:互联网

题:https://codeforces.com/contest/1373/problem/D

题意:翻转1次,求最大偶数位和

分析:先把偶数位的值加起来,然后只能翻转一次,那么要是有翻转奇数位的贡献只能是+a[i]-a[i-1]或+a[i]-a[i+1](这是对于翻转的整个子区间来说的),那么只要求贡献区间的最大子段和即可

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int M=1e6+6;
const int inf=0x3f3f3f3f;
const ll INF=1e18;
#define pb push_back
#define MP make_pair
ll a[M],maxx[M],b[M];
int main(){
    int t;
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        ll ans=0;
        for(int i=1;i<=n;i++){
            cin>>a[i];
            if(i&1)
                ans+=a[i];
        }
        int tot=0;
        for(int i=1;i<=n;i+=2)
            if(i+1<=n)
                b[++tot]=-a[i]+a[i+1];
        maxx[1]=b[1];
        ll tmp1=maxx[1];
        for(int i=2;i<=tot;i++){
            if(maxx[i-1]>0)
                maxx[i]=maxx[i-1]+b[i];
            else
                maxx[i]=b[i];
            tmp1=max(tmp1,maxx[i]);
        }
        ///
        tot=0;
        for(int i=1;i<=n;i+=2)
            if(i-1>=1)
                b[++tot]=-a[i]+a[i-1];
        maxx[1]=b[1];
        ll tmp2=maxx[1];
        for(int i=2;i<=tot;i++){
            if(maxx[i-1]>0)
                maxx[i]=maxx[i-1]+b[i];
            else
                maxx[i]=b[i];
            tmp2=max(tmp2,maxx[i]);
        }
        cout<<max(ans,max(tmp1+ans,tmp2+ans))<<endl;
    }
    return 0;
}
View Code

 

标签:Even,maxx,const,int,Positions,Sum,tmp2,ll,翻转
来源: https://www.cnblogs.com/starve/p/13284421.html