zoukankan      html  css  js  c++  java
  • HDOJ 1231 最大连续子序列

    最大连续子序列

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


    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 -210-10 1 2 3 4 -5 -23 3 7 -2165 -8 3 2 5 01103-1 -5 -23-1 0 -20
     

    Sample Output
    20 11 1310 1 410 3 510 10 100 -1 -20 0 0
    Hint
    Hint
    Huge input, scanf is recommended.
     

    Source
     

    Recommend
    JGShining
     

     
    #include <cstring>
    #include <iostream>
    #include <cstdio>

    using namespace std;

    int num[10010];

    int main()
    {
        int n;
        while(scanf("%d",&n)&&n)
        {
            memset(num,0,sizeof(num));
            int OK=0;
            for(int i=0;i<n;i++)
            {
                scanf("%d",&num);
                if(num>=0) OK=1;
            }
            if(OK)
            {
                int s=0,e=0;
                int sum=0; int temp=0;
                int maxn=-999999993;
                for(int i=0;i<n;i++)
                {
                    if(sum<0)
                    {
                        temp=i;
                        sum=0;
                    }
                    sum+=num;
                    if(sum>maxn)
                    {
                        maxn=sum;
                        e=i;
                        s=temp;
                    }
                }

    //            printf("%d-->%d\n",s,e);
                printf("%d %d %d\n",maxn,num[s],num[e]);
            }
            else if(OK==0)
            {
                printf("%d %d %d\n",0,num[0],num[n-1]);
            }

        }

        return 0;
    }

  • 相关阅读:
    day12 Python操作rabbitmq及pymsql
    day11 队列、线程、进程、协程及Python使用缓存(redis/memcache)
    day10 Python作用域 Python2.7与Python3.x的类继承的区别、异步IO、多进程,多线程简介
    day09 Python socket编程
    day08 面向对象补充及单例模式
    day07 configparser xml subprocess 面向对象
    day06 Python的一些内建变量、反射、hashlib模块、re模块、os模块、sys模块
    day05 Python多层装饰器、模块、序列化、字符串格式化、生成器和迭代器、递归、time、datetime模块、logging模块
    day04 Python一些内置函数及装饰器
    查看旧版jexus命令
  • 原文地址:https://www.cnblogs.com/CKboss/p/3351060.html
Copyright © 2011-2022 走看看