HDU-1003 Max Sum(最大連續子段和)

原題鏈接 http://acm.hdu.edu.cn/showproblem.php?pid=1003

Max Sum

Problem Description

Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).

Output

For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.

Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
 
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6


 Source Code

/**
* 動態規劃:計算最大子段和
* 算法描述:
* 數組a[]有n個元素, 記 s[i] 爲從a[0]到a[i]中,((包含a[i]))的最大子段和 s[i] = max(s[i - 1] + a[i], a[i]),
   然後在s[0]到s[i]裏找出最大值就是a[]的最大子段和
* 即: s[i] 的值爲:  s[i-1]>0時,s[i] = s[i - 1]+a[i];
* 					否則 s[i] = a[i]
*/


#include <iostream>
using namespace std;

//記錄最大子段和的起點,終點,值
int start, end, MaxValue;

void MaxSum(int *array, int len) {
	int i, newStart = 0;
	int sum = 0;
    for (i = 0; i < len; i++) {
		if (sum < 0) {
			sum = array[i];
			newStart = i;
		} else {
            sum += array[i];
		}

		if (sum > MaxValue) {
			MaxValue = sum;
			start = newStart;
			end = i;
		}
	}

}

int main() {
	int cases, len, i, j;
	int num[100001];
	while (scanf("%d", &cases) != EOF) {

		for (j = 1; j <= cases; j++) {
			scanf("%d", &len);
			for(i = 0; i < len; i++) {
				scanf("%d", &num[i]);
			}
			MaxValue = num[0];
			start = end = 0;
			MaxSum(num, len);
			printf("Case %d:\n", j);
			printf("%d %d %d\n", MaxValue, start + 1, end + 1);

			if (j != cases) printf("\n");
		}
	}
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章