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

    给定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

    写得有点丑~~~
     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstdio>
     4 using namespace std;
     5 
     6 int K;
     7 int a[10005],dp[10005];
     8 
     9 int main()
    10 {  while(~scanf("%d",&K)&&K!=0){
    11        
    12           int t=0;
    13           for(int i=1;i<=K;i++){
    14                  scanf("%d",&a[i]);
    15                  if(a[i]<0) t++;
    16           }
    17           if(t==K) printf("%d %d %d
    ",0,a[1],a[K]);
    18           else{
    19                  int sum=0,maxsum=-1e9,ans=-1e9,l=1,r=1,temp=1;
    20                  dp[0]=0;
    21                  for(int i=1;i<=K;i++){
    22                       dp[i]=max(dp[i-1]+a[i],a[i]);
    23                       ans=max(ans,dp[i]);
    24                  }     
    25                  for(int i=1;i<=K;i++){
    26                       sum+=a[i];
    27                       if(sum>maxsum){
    28                             maxsum=sum;
    29                             l=temp;
    30                             r=i;
    31                       }
    32                       if(sum<0){
    33                             sum=0;
    34                             temp=i+1;
    35                       }
    36                       if(ans==maxsum) break;
    37                  }
    38                  printf("%d %d %d
    ",ans,a[l],a[r]);
    39              }        
    40    }
    41 }
  • 相关阅读:
    GDOI模拟赛Round 1
    Codeforces 241B
    Codeforces 325E
    Codeforces 235E
    Codeforces 293B
    Codeforces 263E
    快速傅里叶变换FFT
    后缀自动机
    NOI2011 Day2
    NOI2014 Day2
  • 原文地址:https://www.cnblogs.com/zgglj-com/p/6810423.html
Copyright © 2011-2022 走看看