CodeForces - 1373D Maximum Sum on Even Positions(最大連續子段和)

題目鏈接:點擊查看

題目大意:給出一個長度爲 n 的數列 a ,允許選擇一個子串進行翻轉,問最後可以得到的,偶數位置的數字之和的最大值是多少

題目分析:模擬幾次不難發現,我們翻轉的長度必須是偶數纔能有貢獻,如果是奇數的話翻轉前後沒什麼區別的

所以我們不妨初始時記錄一下偶數位置的數值之和爲 sum ,如果對一段長度爲偶數的區間進行翻轉的話,那麼肯定是減去偶數位置的值,加上奇數位置的值作爲貢獻,換句話說,奇數位置與偶數位置的數值之差便是翻轉之後貢獻所在,所以我們可以對奇數位置與偶數位置之差求一下最大連續子段和,也就對應着題目中說的選擇一段子串進行翻轉,因爲對於一個偶數的位置 i 來說,可能是 i 與 i - 1 交換,也可能是 i 與 i + 1 交換,所以需要分兩種情況然後取最大值

代碼:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=2e5+100;

int a[N],n;

LL solve()
{
	LL max_ending=0,mmax=0;
	for(int i=0;i<n-1;i+=2)//a[0],a[1]
	{
		max_ending=max(0LL,max_ending+a[i+1]-a[i]);
		mmax=max(mmax,max_ending);
	}
	max_ending=0;
	for(int i=1;i<n-1;i+=2)//a[1],a[2]
	{
		max_ending=max(0LL,max_ending+a[i]-a[i+1]);
		mmax=max(mmax,max_ending);
	}
	return mmax;
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	int w;
	cin>>w;
	while(w--)
	{
		scanf("%d",&n);
		LL ans=0;
		for(int i=0;i<n;i++)
		{
			scanf("%d",a+i);
			if(i%2==0)
				ans+=a[i];
		}
		printf("%lld\n",ans+solve());
	}










    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章