Maximum sum

描述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<bits/stdc++.h>  
using namespace std;  
int n,maxn,a[50001],f[50001],g[50001],F[50001],G[50001];  
main()  
{  
    int t;  
    cin>>t;  
    while(t--)  
    {  
        maxn=-20001;  
        cin>>n>>a[1];  
        int mxf=F[1]=f[1]=a[1];  
        for(int i=2;i<=n;i++)  
        {  
            cin>>a[i];  
            f[i]=a[i]+max(0,f[i-1]);    //找出在a[1]……a[i]序列中以a[i]为结尾的和最大子序列  
            mxf=F[i]=max(mxf,f[i]); //找出在a[1]……a[i]序列中的和最大子序列(不一定包含a[i])  
        }  
        int mxg=G[n]=g[n]=a[n];  
        for(int i=n-1;i>0;i--)  
        {  
            g[i]=a[i]+max(0,g[i+1]);    //找出在a[i]……a[n]序列中以a[i]为开头的和最大子序列  
            mxg=G[i]=max(mxg,g[i]); //找出在a[i]……a[n]序列中的和最大子序列(不一定包含a[i])  
        }  
        for(int i=1;i<n;i++)        //枚举断点  
            if(F[i]+G[i+1]>maxn) //G[i+1]是因为不可有重叠部分  
                maxn=F[i]+G[i+1];  
        cout<<maxn<<endl;  
    }  
}  

//实在是完美。

PS:就是求取左边连续的最大值,右边连续的最大值。

注意F(i)与G(i),分别保存从1到i中不一定包括i的连续最大值,与i到n不一定包括i的连续最大值,

f(i)中保存1到i的以a[i]为结尾的连续和最大子序列和,但是mxf会保存那个较大的,如果当前是负数,那么肯定就还是使用原来的最大值。

猜你喜欢

转载自blog.csdn.net/huanting74/article/details/80210173
今日推荐