Given a sequence of K integers { N 1 , N 2 , ..., N K }. A continuous subsequence is defined to be { N i , N i+1 , ..., N j } 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
本题是 01-复杂度1 最大子列和问题 这个问题的升级版,需要考虑多种情况,如果考虑不全面就会丢分,还有要注意看清楚题目要求,是要输出 最大子列和 和 首尾的元素值。
参考代码
#include <stdio.h>
#include <stdlib.h>
#define maxn 100004
int a[maxn];
int main(){
int i,k,flag,sign;
flag=0,sign=0;
while(scanf("%d",&k)!=EOF){
for(i=0;i<k;i++){
scanf("%d",&a[i]);
if(a[i]>=0){
flag=1;//flag=1表示出现了非负数
}
if(a[i]>0){
sign=1;//sign=1表示出现了正数
}
}
if(k==1){/*如果只有一个数据*/
if(a[0]<0){/*只有一个负的数据*/
printf("%d %d %d\n",0,a[0],a[0]);
}
else{/*只有一个正数据*/
printf("%d %d %d\n",a[0],a[0],a[0]);
}
}
else{
int maxSum,thisSum,start,end,c;
c=start=end=thisSum=0;
maxSum=-1;
for(i=0;i<k;i++){
thisSum+=a[i];
if(thisSum>maxSum){
maxSum=thisSum;
end=i;/*更新子列和开始和结束坐标*/
start=c;
}
else if(thisSum<0){
thisSum=0;
c=i+1;/*先将子列和开始坐标记录下来*/
}
}/*sign==0&&flag==1说明全部都是小于等于零的数据,没有正数据*/
if(sign==0&&flag==1){
printf("0 0 0\n");
}/*flag==0说明全部都是负数*/
else if(flag==0){
printf("%d %d %d\n",0,a[0],a[k-1]);
}
else{
printf("%d %d %d\n",maxSum,a[start],a[end]);
}
}
}
return 0;
}
第二次做的代码
#include <iostream>
#include <stdio.h>
using namespace std;
#define maxn 100000
int a[maxn];
int main()
{
int n,i,ts,s,e,thisSum,maxSum;
scanf("%d",&n);
ts=thisSum=maxSum=0;
int flag,sign;
flag=sign=0;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
if(a[i]==0){
flag=1;
}
if(a[i]>0){
sign=1;
}
}
s=e=0;
for(i=0; i<n; i++)
{
thisSum+=a[i];
if(thisSum>maxSum)
{
maxSum=thisSum;
s=ts; e=i;
//printf("e=%d\n",e);
}
else if(thisSum<0)
{
thisSum=0;
ts=i+1;
//printf("s=%d\n",s);
}
}
if(flag==0&&sign==0)// if all numbers are negative
{
printf("0 %d %d",a[0],a[n-1]);
}
else if(flag==1&&sign==0){ // negative and zero
printf("0 0 0\n");
}
else
{
printf("%d %d %d",maxSum,a[s],a[e]);
}
return 0;
}