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.


大意是说在给定的数列中,选取两段不重合的子串,使得其和最大。
写在前面:一个要注特别意的问题,WA的可能就是忽略了这个问题。
|ai| <= 10000,即可能有负数,那么初始化为0就不行了,0比负数大呀!怎么办呢,要么赋一个极小值,要么初始化为数列中的开始元。
还有一个小问题,呃,也不是什么问题,就是要注意一下数组的值的清空,因为即使定义在循环内部,他的生命周期结束了,可有可能下次分配到的地址还是在那里,里面的值并没有改变。
另外,对于多个字节的类型,memset只能初始化为 0 ,-1。不信的可以试试,一个整型四个字节,他会把每个字节都的二进制的每一位都赋值为目标数字……好像是这样,应该不对,反正不能赋值为其他值


#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int data[50005],l[50005],r[50005],mid[50005];
int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        int n;
        scanf("%d",&n);
        for(int i = 1; i<=n; i++) {
            scanf("%d",&data[i]);
        }
        l[1] = data[1];
        for(int i = 2; i<=n; i++) {
            l[i] = 0; 
            l[i] = max(data[i],l[i-1] + data[i]);
        }
        r[n] = data[n];
        for(int i = n-1; i>=1; i--) {
            r[i] = 0;
            r[i] = max(r[i+1] + data[i],data[i]);
        }
        mid[n] = r[n];
        for(int i = n - 1; i>=1; i--) {
            mid[i] = 0;
            mid[i] = max(r[i],mid[i+1]);
        }
        int ans = -1e9;
        for(int i = 2;i<=n;i++){
            ans = max(ans,l[i-1] + mid[i]);
        }
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2018-01-30 22:40  WenOI  阅读(332)  评论(0编辑  收藏  举报
水波背景