描述
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
t1 t2
d(A) = max{ ∑ai + ∑aj | 1 <= s1 <= t1 < s2 <= t2 <= n }
i=s1 j=s2
Your task is to calculate d(A).
输入
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.
输出
Print exactly one line for each test case. The line should contain the integer d(A).
样例输入
1
10
1 -1 2 2 3 -3 4 -4 5 -5
样例输出
13
提示
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
来源
POJ Contest,Author:Mathematica@ZSU
题解
#include<cstdio>
#define M -9999999
#define L 50050
int a[L],f[L];
int main()
{
int t,n,max,min,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(f[i-1]>0)f[i]=f[i-1]+a[i];
else f[i]=a[i];
}
ans=0,max=M,min=M;
for(int i=n;i>1;i--)
{
ans+=a[i];
if(ans>max)max=ans;
if(min<max+f[i-1])min=max+f[i-1];
if(ans<0)ans=0;
}
printf("%d\n",min);
}
return 0;
}
思路
动态规划。
思路很简单,就是求出一个数的左右两个子序列然后找最大值,那么设left,right,leftmax,rightmax四个数组。
left[i]表示到包含第i位其左子序列的最大值,易得left[i]=max(left[i-1]+a[i],a[i]);
leftmax[i]表示到第i位时其左子序列的最大值(包含a[i]),易得leftmax[i]=max(leftmax[i-1],left[i]),
right[i]表示不包含第i位其右子序列的最大值(主要是为了避免重叠,这样子好算很多),易得right[i]=max(right[i+1],right[i+1]+a[i+1])
rightmax[i]表示到第i位时其右子序列的最大值(不包含a[i]),易得rightmax[i]=max(rightmax[i+1],right[i]);
然后加起来最大值就好了。