• hdu---1231---最大连续子序列


    http://acm.hdu.edu.cn/showproblem.php?pid=1231

    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
    
    
            
     
    Huge input, scanf is recommended.
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <cmath>
    #include<vector>
    #include<algorithm>
    using namespace std;
    #define PI 3.1415926
    
    const int maxn=10007;
    const int INF=0x3f3f3f3f;
    
    int a[maxn];
    int main()
    {
        int n;
        while(scanf("%d", &n), n)
        {
            for(int i=1; i<=n; i++)
                scanf("%d", &a[i]);
    
            int nows=1, Start=1, End=1;
            int sum, Max;
            sum=Max=a[1];
            for(int i=2; i<=n; i++)
            {
                if(sum+a[i]<a[i])
                {
                    sum=a[i];
                    nows=i;///用来记录最大连续序列的开始的下标
                }
                else
                    sum+=a[i];
    
                if(sum>Max)
                {
                    Max=sum;
                    Start=nows;
                    End=i;
                }
            }
    
            if(Max<0)///如果全为负数的话,肯定最大值也为负数,只要有一个正数,就能找到最大连续子序列
                printf("0 %d %d
    ", a[1], a[n]);
            else
                printf("%d %d %d
    ", Max, a[Start], a[End]);
        }
        return 0;
    }
  • 相关阅读:
    关于事件的分发与传递
    Android直播app用什么技术可以做到延迟小一些?
    android菜鸟求教eclipse创建avd问题
    安卓APP集成支付宝,调用支付接口,直接退出程序了
    关于蓝牙socket 服务器端首次accept总出错!
    【求助】Android 4.4.2 的WebView的问题
    android 4.0.3开机时不能收到广播
    vue 应用 :关于 ElementUI 的 message 组件
    vue 应用 : 计数器组件
    vue 应用 :多语言显示
  • 原文地址:https://www.cnblogs.com/w-y-1/p/5748561.html
Copyright © 2020-2023  润新知