原题 (最大字段和)
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
翻译如下:
给定一个序列 a[1],a[2],a[3]…a[n],你的工作是计算一个子序列的最大和。 例如,给定 (6,-1,5,4,-7),此序列中的最大和为 6 + (-1) + 5 + 4 = 14。
输入
输入的第一行包含一个整数 T(1<=T<=20),表示测试用例的数量。 然后是 T 行,每行以一个数字 N(1<=N<=100000) 开始,然后是 N 个整数(所有整数都在 -1000 和 1000 之间)。
输出
对于每个测试用例,您应该输出两行。 第一行是“Case #:”,#表示测试用例的编号。 第二行包含三个整数,序列中的最大和,子序列的开始位置,子序列的结束位置。 如果有多个结果,则输出第一个。 在两种情况之间输出一个空行。
样本输入
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
样本输出
情况1:
14 1 4
案例2:
7 1 6
解题思路
对于每次输入的序列中的值,我们都用一个 sum 记录某一个子序列的和,sum初始值为 0 。先假设最大子序列起始于 1 ,终止于 1 。由于序列中的所有整数都在 -1000 和 1000 之间,那么我们也预设最大字段和的值为 -1000 。
int sum = 0, start = 1, end = 1, max = -1000;
我们还要设一个 next_start 用来代表可能成为下一个更大子序列的起点,只有 最大值 max 有了新高才会更新 start = next_start
int next_start = 1;
每次输入的序列中的值 x ,都会经过以下操作
for (int n = 1; n <= N; n++) {
cin >> x; //输入该数字的值
sum += x; //求和
if (sum > max) { //sum 有了新高
max = sum ; //刷新最大值
start = next_start; //刷新最大子序列的起点
end = n; //刷新最大子序列的终点
}
//当 sum<0 时,说明前面的一段子序列到n为止不再适合加入后面的子序列
//若加入,则会使后面的子序列的和降低,因此重置 sum = 0
//next_start 为下一个数的位置,代表可能成为下一个更大子序列的起点
if (sum < 0) {
sum = 0;
next_start = n + 1;
}
}
题解
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
using namespace std;
int main()
{
int T, N; //T组数据,每组数据有N个值
cin >> T;
for (int t = 1; t <= T; t++) {
int next_start = 1, start = 1, end = 1, max = -1000, sum = 0, x;
cin >> N;
for (int n = 1; n <= N; n++) {
cin >> x;
sum += x;
if (sum > max) {
max = sum ;
start = next_start;
end = n;
}
if (sum < 0) {
sum = 0;
next_start = n + 1;
}
}
cout << "Case " << t << ":" << endl;
cout << max << " " << start << " " << end << endl;
if (t != T) cout << endl;
}
return 0;
}