hdu 1231 最大连续子序列

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

分析:求最大连续子序列之和及首尾元素,开始还是用了枚举(时间复杂度O(n^2)(解法一),TLE。 后来发现可以把复杂度优化到O(n)..(解法二).

/*最大连续子序列

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21045    Accepted Submission(s): 9331


Problem Description
给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., 
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个, 
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和 
为20。 
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该 
子序列的第一个和最后一个元素。
 

Input
测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。
 

Output
对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元 
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。 
 

Sample Input
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
 

Sample Output
20 11 13
10 1 4
10 3 5
10 10 10
0 -1 -2
0 0 0

Hint
Hint
 
Huge input, scanf is recommended.
 

Source
浙大计算机研究生复试上机考试-2005年
*/
//解法一:复杂度O(n^2)
//Time Limit out
#include <cstdio>
#include <cstring>
const int maxn = 10000 + 10;
int a[maxn];
int main()
{
    int k;
    while(~scanf("%d", &k) && k){
        int flag = 0;//创建标记,若数组元素都为负则按题意输出
        for(int i = 0; i < k; i++){
            scanf("%d", &a[i]);
            if(a[i] >= 0) flag = 1;
        }
        if(!flag){
            printf("0 %d %d
", a[0], a[k-1]);
            continue;
        } 
        int A = 0, Max = -0xffff, s, e;
        while(A < k){
        //遍历数组,存储更新最大子序列的和与下标
            int cnt = 0;
            for(int B = A; B < k; B++){
                cnt += a[B];
                if(cnt > Max){
                    Max = cnt;
                    s = A;
                    e = B;
                }
            }
            A++;
        }
        printf("%d %d %d
", Max, a[s], a[e]);    
    }
    return 0;
}

//解法二:复杂度O(n)
//Accept
#include <cstdio>
#include <cstring>
const int maxn = 10000 + 10;
int a[maxn];
int main()
{
    int k;
    while(~scanf("%d", &k) && k){
        int flag = 0; //处理数组全部为负的情况
        for(int i = 0; i < k; i++){
            scanf("%d", &a[i]);
            if(a[i] >= 0) flag = 1;
        }
        if(!flag){
            printf("0 %d %d
", a[0], a[k-1]);
            continue;
        } 
        int Max = -0xffff, s = 0, e = 0, cnt = 0;
        for(int A = 0, B = 0; A < k; A++){
                //遍历数组,数组和小于零则清零,以及更新最大和
            cnt += a[A];
            if(cnt < 0){
                cnt = 0;
                B = A+1;
            }
            else if(cnt > Max){
                Max = cnt;
                s = B;
                e = A;
            }        
        }
        printf("%d %d %d
", Max, a[s], a[e]);    
    }
    return 0;
}
    
原文地址:https://www.cnblogs.com/ACFLOOD/p/4369759.html