poj2479

Maximum sum
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25093   Accepted: 7623

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.





这是一个求最大子段和的问题。但是是两个最大子段和的问题。首先从左到右求最大子段和,再从右到左求最大子段和将其相加。。
#include<iostream>
#include<stdio.h>
using namespace std;
int a[50000+1];
int left1[50000+1];
int right1[50000+1];
int main()
{
    freopen("in.txt","r",stdin);
    int t;
    int n;
    scanf("%d",&t);
    while(t)
    {
        t--;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        left1[1]=a[1];//从左到右求最大子段和。。
        for(int i=2;i<=n;i++)//求前i个元素的最大子段和
        {
            left1[i]=(left1[i-1]>0)?(left1[i-1]+a[i]):a[i];
        }
        for(int i=2;i<=n;i++)
        {
            left1[i]=max(left1[i-1],left1[i]);
        }
        right1[n]=a[n];//从右到左求最大子段和
        for(int i=n-1;i>=1;i--)
        {
            right1[i]=(right1[i+1]>0)?(right1[i+1]+a[i]):a[i];
        }
        for(int i=n-1;i>=1;i--)//求从i到n的最大子段和
        {
            right1[i]=max(right1[i+1],right1[i]);
        }
        int max=left1[1]+right1[2];
        for(int i=2;i<n;i++)
        {
            if(max<left1[i]+right1[i+1])
            {
                max=left1[i]+right1[i+1];
            }
        }
        cout<<max<<endl;
    }
    return 0;
}


你可能感兴趣的:(poj2479)