码迷,mamicode.com
首页 > 其他好文 > 详细

poj2593 Max Sequence(求两个不相交最大字段和)

时间:2014-07-13 17:28:10      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:数学   poj   遍历   

转载请注明出处:http://blog.csdn.net/u012860063?viewmode=contents

题目链接:http://poj.org/problem?id=2593

Description

Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N). 
bubuko.com,布布扣

You should output S. 

Input

The input will consist of several test cases. For each test case, one integer N (2 <= N <= 100000) is given in the first line. Second line contains N integers. The input is terminated by a single line with N = 0.

Output

For each test of the input, print a line containing S.

Sample Input

5
-5 9 -5 11 20
0

Sample Output

40

 思想:对于数据a[],从左向右依次求解以a[i]结尾的最大子段和b[i],
  然后,从右向左遍历,求a[i]右边(包括a[i])的最大子段和sum,输出sum+b[i-1]的  最大值。

代码如下:

#include <iostream>
using namespace std;
#define INF 0x3fffffff
#define M 100000+17
int a[M],b[M];
int main()
{
	int n,i;
	while(cin >> n && n)
	{
		int sum = 0, MAX = -INF;
		for(i = 1; i <= n; i++)
		{
			cin >> a[i];
			sum+=a[i];
			if(sum > MAX)
			{
				MAX = sum;
			}
			b[i] = MAX;
			if(sum < 0)
			{
				sum = 0;
			}
		}
		MAX = -INF;
		sum = 0;
		int ans = MAX, t;
		for(i = n; i > 1; i--)
		{
			sum+=a[i];
			if(sum > MAX)
			{
				MAX = sum;
			}
			t = MAX + b[i-1];
			if(t > ans)
			{
				ans = t;
			}
			if(sum < 0)
			{
				sum = 0;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}


poj2593 Max Sequence(求两个不相交最大字段和),布布扣,bubuko.com

poj2593 Max Sequence(求两个不相交最大字段和)

标签:数学   poj   遍历   

原文地址:http://blog.csdn.net/u012860063/article/details/37728869

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!