hdu 1231最长连续子序列的和

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1231

题目解析:这个题目和之前做的求最长连续子序列的和是一样,但是还要输出子序列的开始和结尾,所以做法有点不同,其次注意细节,就是当序列的元素都是负数的时候,和为0

代码:

/*
6
-2 11 -4 13 -5 -2
10
-10 1 2 3 4 -5 -23 3 7 -21
6
5 -8 3 2 5 0
1
10
3
-1 -5 -2
3
-1 0 -2
0
*/
/*
20 11 13
10 1 4
10 3 5
10 10 10
0 -1 -2
0 0 0

*/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<string>
using namespace std;
int a[10000];
int main(){
	int k,i,temp,sum,begin,end,tb;
	while(scanf("%d",&k),k){
		for(i=0;i<k;i++)
			scanf("%d",&a[i]);
		temp=begin=end=tb=0;
		sum=-1;
		for(i=0;i<k;i++){
			temp+=a[i];
			if(temp>sum){
				sum=temp;
				end=i;
				begin=tb;
			}
			if(temp<0){
				temp=0;
				tb=i+1;
			}
		}
		if(sum==-1){
			sum=0;
			begin=0;
			end=k-1;
		}
		printf("%d %d %d\n",sum,a[begin],a[end]);
	}
	return 0;
}



你可能感兴趣的:(hdu 1231最长连续子序列的和)