poj----Maximum sum(poj 2479)

Maximum sum
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 30704   Accepted: 9408

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:

poj----Maximum sum(poj 2479)

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
题意:
给一个数列,求出数列中不相交的两个字段和,要求和最大。
思路:
对每一个i来说,求出【0~i-1】的最大子段和以及【i~n-1】的最大子段和,再加起来求最大的一个就行了。[0~i-1]的最大子段和从左向右扫描,【i~n-1】从右想左扫描
即可,时间复杂度O(n).
代码:
 #include<iostream>
#include<cstdio>
#define maxn 50001
#include<algorithm>
using namespace std;
int a[maxn];
int left[maxn];
int right[maxn];
int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
int t,i;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(i=;i<n;i++)
scanf("%d",&a[i]);
//此时::left【i】为包涵i最大字段和
::left[]=a[];
for( i=; i<n;i++)
if(::left[i-]<)
::left[i]=a[i];
else
::left[i]=::left[i-]+a[i];
//此时left[i]为i左边最大字段和
for(i=; i<n;i++)
::left[i]=max(::left[i],::left[i-]);
::right[n-]=a[n-];
for(i=n-;i>=;i--)
{
if(::right[i+]<)
::right[i]=a[i];
else
::right[i]=::right[i+]+a[i];
}
for(i=n-;i>=;i--)
::right[i]=max(::right[i+],::right[i]);
int res=-;
for(i=;i<n;i++)
{
res=max(res,::left[i-]+::right[i]);
}
printf("%d\n",res);
}
return ;
}
上一篇:【转】MOCK方法介绍


下一篇:POJ 2479 Maximum sum POJ 2593 Max Sequence