题目描述:
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 -21
Sample Output:
10 1 4
题目大意:
给定一个由K个整数组成的序列{N-1,N2 …,NK}。连续的子序列定义为{N i,N i + 1,…,N j}}其中1≤i≤j≤K。最大子序列是具有最大元素和的连续子序列。例如,给定序列{-2,11,-4,13,-5,-2},其最大子序列为{11,-4,13},最大和为20。
现在,您应该找到最大的和,以及最大子序列的第一个和最后一个数字。
输入规格:
每个输入文件包含一个测试用例。每个案例占用两行。第一行包含一个正整数K(≤10000)。第二行包含K个数字,以空格分隔。
输出规格:
对于每个测试用例,在一行中输出最大和,以及最大子序列的第一个和最后一个数字。数字必须用一个空格分隔,但行尾不能有多余的空格。如果最大子序列不是唯一的,则输出索引i和j最小的子序列(如示例情况所示)。如果所有K个数字均为负,则其最大和定义为0,并且应该输出整个序列的第一个和最后一个数字。
分析:
设一个临时变量temp存放所有可能的子序列的和,若该子序列的元素和大于sum(最终子序列),则将temp所存放的子序列赋给sum,同时更新sum的左右边界的下标,由此不断更新最优解
注意:序列只有负数和0的情况需要特殊考虑
1、将sum初始值赋为-1
2、如下:
#include <iostream>
using namespace std;
int Array[10001];
int main() {
int n, i, sum = 0, flag = 0, tempSum = 0;
int tempIndex[3], Index[3];
tempIndex[0] = 0; tempIndex[1] = -1;
cin >> n;
Index[0] = 0; Index[1] = n - 1;
for (i = 0; i < n; i++) {
cin >> Array[i];
if (Array[i] >= 0)
flag = 1;
tempSum += Array[i];
tempIndex[1]++;
if (tempSum > sum || (tempSum == sum && (Index[1] == n-1 && Index[0] == 0))) {
sum = tempSum;
Index[0] = tempIndex[0];
Index[1] = tempIndex[1];
}
if (tempSum < 0) {
tempIndex[0] = i + 1;
tempIndex[1] = i;
tempSum = 0;
}
}
if (flag == 0)
cout << '0' << ' ' << Array[Index[0]] << ' ' << Array[Index[1]] << endl;
else
cout << sum << ' ' << Array[Index[0]] << ' ' << Array[Index[1]] << endl;
return 0;
}