原题链接 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");
}
}
}