HDU1231 最大连续子序列 DP

最大连续子序列

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


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
 


题意及思路:统计区间最大和,比较烦的是还要写出区间和的左右边界的值,右值好说,左值还要小心处理一下,而且在相同答案的情况下还要输出最左边的一组数据。


#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <iomanip>
#include <time.h>
#include <set>
#include <map>
#include <stack>
using namespace std;
typedef long long LL;
const int INF=0x7fffffff;
const int MAX_N=10000;

int K;
int A[10009];
int main(){
    while(scanf("%d",&K)&&K!=0){
        int flag=0;
        for(int i=0;i<K;i++){
            scanf("%d",&A[i]);
            if(A[i]>=0){
                flag=1;
            }
        }

        if(flag==0){
            cout<<0<<" "<<A[0]<<" "<<A[K-1]<<endl;
        }
        else{
            int ans=-1,ansl=A[0],ansr,curans=0,curl;
            for(int i=0;i<K;i++){
                if(A[i]>0){
                    curans+=A[i];
                    if(curans-A[i]<=0){
                        curl=A[i];
                    }
                    if(curans>ans){
                        ans=curans;
                        ansr=A[i];
                        ansl=curl;
                    }
                }
                else{
                    curans+=A[i];
                    if(curans<0){
                        curans=0;
                    }

                    if(A[i]==0&&curans>ans){
                        ansl=0;
                        ansr=0;
                        ans=0;
                    }
                }
            }
            cout<<ans<<" "<<ansl<<" "<<ansr<<endl;
        }


    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值