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

    题面

    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

    思路

    dp基础题,求最大连续子序列,用一个dp数组加上前一个元素的值判断是否大于0就可以了,相当于一个前缀和,而每当出现一个负元素,那么这个元素就不会进行dp累加,相当于重新开始一段子序列,在求解过程中记录每一次大于ans值的dp序列的left和right值就好了。

    代码实现

    #include<cstdio>
    #include<algorithm>
    #include<cmath>
    #include<cstring>
    #include<iostream>
    #include<vector>
    using namespace std;
    #define eps 1e-4
    const int maxn=50005;
    int a[maxn], dp[maxn];
    int n;
    int main () {
       while (cin>>n) {
          int start,end;
          int ans=0;
          memset (a,0,sizeof (a));
          if (n==0) {
             break;
          }
          int p=1,left=1,right=1,all=0;
          int maxnum=-1;
          for (int i=1;i<=n;i++) {
             cin>>a[i];
             if (a[i]>all) all=1;
             if (a[i]<0) ans++;
             if (i==1) start = a[i];
             if (i==n) end = a[i];
             if (a[i-1]>0) a[i]+=a[i-1];
             else p=i;
             if (a[i]>maxnum) {   
                maxnum = a[i];
                left = p;
                right = i;
             }
          }
          if (ans==n) cout<<0<<" "<<start<<" "<<end<<endl; 
          else if (all==0) cout<<0<<" "<<0<<" "<<0<<endl;
          else cout<<maxnum<<" "<<a[left]<<" "<<a[right]-a[right-1]<<endl;
          
       }
        return 0;
    }
    
  • 相关阅读:
    无线路由器wds桥接技术+丢包率
    2016CCPC东北地区大学生程序设计竞赛1008/HDU 5929 模拟
    Codeforces Round #375 (Div. 2) A B C 水 模拟 贪心
    Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) A B C D 水 模拟 并查集 优先队列
    Codeforces Round #310 (Div. 2) A B C
    Codeforces Round #374 (Div. 2) A B C D 水 模拟 dp+dfs 优先队列
    Codeforces Round #313 (Div. 2) A B C 思路 枚举 数学
    Codeforces Round #373 (Div. 2) A B C 水 贪心 模拟(四舍五入进位)
    CentOS7 PostgreSQL 安装
    数据库事务的隔离级别
  • 原文地址:https://www.cnblogs.com/hhlya/p/13132566.html
Copyright © 2011-2022 走看看