最近开始复习数据结构,选择去看浙江大学的慕课,里面的测验和作业基本都是PTA上面的,记录下代码与有关注释。
这道题是求最大子列和,但是增加了需要输出子列和的开始与结束元素,需要注意的是全部为负数以及最大子列和中大部分为0的情况。
题目
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
代码实现:犯的错都以里面注释的方式展现出来了
#include <iostream>
using namespace std;
int main()
{
int n,a,i,A[100000];
int sum = 0,maxsum = 0,start = 0,end2 =0;
bool flag = false;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>a;
if(a>=0) flag = true;//刚开始写了a>0,这样使得如果全是0和负数的话,也会执行这个判断,实际上应该输出0 0 0
A[i]=a;
}
if(!flag)
{
cout<<"0"<<" "<<A[0]<<" "<<A[n-1]<<endl;
}
else
{
for(i=0; i<n; i++)
{
sum += A[i];
if(sum > maxsum)
{
maxsum = sum;
end2 = i;
}
else if(sum < 0)
{
sum = 0;
//start = i+1;这一块需要注意,不能遇见小于0的就更新,可以回溯去找
}
}
sum=0;
for(i=end2; i>=0; i--)
{
sum+=A[i];
if(sum==maxsum)
{
start = i;
//break;<= 这块犯了一个错误,因为需要找最小下边 比如五个数字0 0 0 0 3 应该输出首字符0和3,如果加上break则会输出3和3
}
}
if(maxsum==0)cout << maxsum<<" "<<"0"<<" "<<"0"<<endl;//这是一个坑,因为如果只有负数和0的话,最大和肯定是0,反之也是。
else
{
cout << maxsum<<" "<<A[start]<<" "<<A[end2]<<endl;
}
}
return 0;
}