Poj 2479 Maximum sum
Maximum sum
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 39500 Accepted: 12340
Description
Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:
Your task is to calculate d(A).
Input
The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, …, an. (|ai| <= 10000).There is an empty line after each case.
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input
1
10
1 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
Source
POJ Contest,Author:Mathematica@ZSU
/*
题意:给一段序列,将这个序列分成两部分,使两部分的最大子段和的和最大.
o(n)维护最大前缀/后缀和.
枚举断点将两端和加起来即可.
正确性显然.
*/
#include<iostream>
#include<cstdio>
#define MAXN 50001
using namespace std;
int f[MAXN],n,s[MAXN],w[MAXN],w2[MAXN],ans;
int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x*f;
}
void slove()
{
f[1]=s[1];w[1]=s[1];
for(int i=2;i<=n;i++)
{
if(f[i-1]>=0) f[i]=f[i-1]+s[i];
else f[i]=s[i];
w[i]=max(w[i-1],f[i]);
}
f[n]=s[n];w2[n]=s[n];
for(int i=n-1;i>=1;i--)
{
if(f[i+1]>=0) f[i]=f[i+1]+s[i];
else f[i]=s[i];
w2[i]=max(w2[i+1],f[i]);
}
for(int i=1;i<=n-1;i++)
ans=max(ans,w[i]+w2[i+1]);
printf("%d\n",ans);
return ;
}
int main()
{
int t;
t=read();
while(t--)
{
n=read();ans=-1e9;
for(int i=1;i<=n;i++)
s[i]=read();
slove();
}
return 0;
}