poj2593 Max Sequence(两个不相交字段的最大总和与)
转载请注明出处:http://blog.csdn.net/u012860063?
题目链接:http://poj.org/problem?id=2593
----------------------------------------------------------------------------------------------------------------------------------------------------------
欢迎光临天资小屋:http://user.qzone.qq.com/593830943/main
----------------------------------------------------------------------------------------------------------------------------------------------------------
Description
Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N).
You should output S.
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; }
版权声明:本文博客原创文章。博客,未经同意,不得转载。