poj2593 2010.2.22
Max Sequence
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 8745 Accepted: 3568
Description
Give you N integers a1, a2 ... aN (|ai|<=1000, 1 <= i <= N).
You should output S.
Input
The input will consist of several testcases. For each test case, one integer N (2 <= N <= 100000) is given inthe first line. Second line contains N integers. The input is terminated by asingle line with N = 0.
Output
For each test of the input, print a linecontaining S.
Sample Input
5
-5 9 -5 11 20
0
Sample Output
40
Source
POJ Monthly--2005.08.28,Li Haoyuan
题目思路:
用两个数组数组记录从前和从后子序列加和的最大值,每个元素的值为从前(后)加和至该位置得到的最大值。
遍历数组每个位置,找出所有位置为分界点的最大值即为结果。
其中得到子序列最大和过程比较特殊,详见代码。
#include <stdio.h>
#include <string.h>
#define MIN -2000000000
#define MAXN 110000
long a[110000],front[110000],back[110000];
void main()
{
long num,i,r,k;
while (scanf("%d",&num),num)
{
for(i=1;i<=num;i++)
scanf("%d",&a[i]);
//要记录下原始数据,否则反方向就不行了
front[0]=MIN;
back[num+1]=MIN;
for(i=1;i<=num;i++)
{
k=(front[i-1]+a[i])>a[i]?(front[i-1]+a[i]):a[i];
front[i]=front[i-1]>k?front[i-1]:k;
}
for(i=num;i>=1;i--)
{
k=(back[i+1]+a[i])>a[i]?(back[i+1]+a[i]):a[i];
back[i]=back[i+1]>k?back[i+1]:k;
}
r=MIN;//刚开始赋值为0了,所以wa掉,因为可能出现全都是负数的情况
//eg:-1 -1 -1 -1 -1 结果应该是-2
for(i=1;i<num;i++)
if (front[i]+back[i+1]>r)
r=front[i]+back[i+1];
printf("%d\n",r);
}
}