题目详情 - 1007 Maximum Subsequence Sum (25 分) (pintia.cn)
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space.
Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Sample Input:
10 -10 1 2 3 4 -5 -23 3 7 -21Sample Output:
10 1 4
测试点分析:
1.当全部为0时;测试点5。
输入:
3
0 0 0
理论输出:
0 0 0
2.全部为负数时:测试点4。
输入:
3
-1 -2 -3
理论输出:
0 -1 -3
3.第一项为0,之后为正数
输入:
3
0 1 3
理论输出
4 0 3
4.如果只有一个数
输入
1
0
输出
0 0 0
输入
1
-1
输出
0 -1 -1
输入
1
1
输出
1 1 1
注意点:
本题如何初始化变量是关键。
1.最大和sum应该初始化为-1:如果初始化为0,当整个序列全部为0时,0可以作为最大子序列和的首项;如果初始化为比-1小的数,若首先为-1,则将-1计入了最大子序列中。
2.最大子序列区间[st,en]中的en应该初始化为K-1:如果全部为负数,则整个区间都将无法更新,而题目要求当全部为负数时,和输出为0,区间输出整个序列的首尾项。
代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int K, x;
cin >> K;
vector<int> v(K);
for (int i = 0; i < K; ++i) { cin >> v[i]; }
int thissum = 0, sum = -1, st = 0, en = K - 1, index = 0;
for (int i = 0; i < K; ++i) {
thissum += v[i];
if (sum < thissum) {
sum = thissum;
st = index;
en = i;
}
else if (thissum < 0) {
thissum = 0;
index = i + 1;
}
}
if (sum < 0)sum = 0;
cout << sum << ' ' << v[st] << ' ' << v[en];
return 0;
}

被折叠的 条评论
为什么被折叠?



