联考20200607 T3 最大子段和

题目:


分析:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<iostream>
#include<map>
#include<bitset>
#include<string>
#include<deque>

#define maxn 10005
#define INF 0x3f3f3f3f

using namespace std;

inline long long getint()
{
	long long num=0,flag=1;char c;
	while((c=getchar())<'0'||c>'9')if(c=='-')flag=-1;
	while(c>='0'&&c<='9')num=num*10+c-48,c=getchar();
	return num*flag;
}

int n,K;
int a[maxn];
int sum[maxn],f[2][maxn],ans;
int now=1,pre;

int main()
{
	n=getint(),K=getint();
	for(int i=1;i<=n;i++)a[2*i-1]=getint();
	a[1]=max(a[1],0),a[2*n-1]=max(a[2*n-1],0);
	for(int i=1;i<2*n;i++)sum[i]=sum[i-1]+(i&1?a[i]:K);
	int k=0;f[pre][0]=0;
	for(int i=1;i<2*n;i++)
	{
		if(a[i]<0)k=i;
		f[pre][i]=max(k?f[pre][k-1]:0,sum[i]-sum[k]);
	}
	ans=sum[2*n-1]-f[pre][2*n-1];
	for(int j=1,k=0;j<n;j++,swap(now,pre))
	{
		memset(f[now],INF,sizeof f[now]);
		deque<int>Q;int i0=0,mx=-INF;
		for(int i=1;i<2*n;i++)
		{
			if(a[i]<0){k=i,i0=i-1,mx-INF;while(!Q.empty())Q.pop_back();}
			f[now][i]=max(k?f[now][k-1]:0,sum[i]-sum[k]);
			if(k==i)continue;
			while(i0+2<=i&&f[pre][i0+1]+sum[i0+2]<=sum[i])i0+=2,mx=max(mx,sum[i0]);
			f[now][i]=min(f[now][i],sum[i]-mx);
			if(!(i&1))
			{
				while(!Q.empty()&&f[pre][Q.back()-1]>=f[pre][i-1])Q.pop_back();
				Q.push_back(i);
			}
			while(!Q.empty()&&Q.front()<=i0)Q.pop_front();
			if(!Q.empty())f[now][i]=min(f[now][i],f[pre][Q.front()-1]);
		}
		ans=max(ans,(sum[2*n-1]-j*(K+1))-f[now][2*n-1]);
	}
	printf("%d\n",ans);
}

posted @ 2020-06-09 21:26  Izayoi_Doyo  阅读(172)  评论(0编辑  收藏  举报