標籤:數學 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).
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 200
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+17int 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;}