zoukankan      html  css  js  c++  java
  • HDU 1003

    Problem Description
    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
     
    Input
    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
     
    Output
    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
     
    Sample Input
    2
    5 6 -1 5 4 -7
    7 0 6 -1 1 -6 7 -5
     

     

    Sample Output
    Case 1:
    14 1 4
     
     
    Case 2:
    7 1 6
     
    题意:
    给你一个序列,求最大连续子列和。
     
    题解:
    定义:dp[i]为从a[1~i]中以a[i]为结尾的最大连续子序列和。
    那么状态转移方程:dp[i] = (dp[i-1]>=0) ? (dp[i-1]+a[i]) : (a[i]));
    最后遍历dp数组,找到最大的那个值就是ans,那个位置就是子序列的末尾位置;
    另外为了记录子序列的开始位置,不妨把dp数组定义成结构体,里面定义一个sum用来存最大的和,另外定义一个st来储存开始位置.
     
    AC代码: 
    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 100000+10;
    
    int a[maxn];
    struct DP{
        int val;
        int st;
    }dp[maxn];
    
    int main()
    {
        int t,n;
        scanf("%d",&t);
        for(int kase=1;kase<=t;kase++)
        {
            scanf("%d",&n);
    
            int maxi=-10000,maxi_idx;
            dp[0].val=-1, dp[0].st=0;
            for(int i=1;i<=n;i++)
            {
                scanf("%d",&a[i]);
                dp[i].val = dp[i-1].val>=0 ? (dp[i-1].val+a[i]) : a[i];
                dp[i].st = dp[i-1].val>=0 ? (dp[i-1].st) : i;
    
                if(maxi<dp[i].val)
                {
                    maxi = dp[i].val;
                    maxi_idx = i;
                }
            }
    
            printf("%sCase %d:
    ",kase>1?"
    ":"",kase);
            printf("%d %d %d
    ",maxi,dp[maxi_idx].st,maxi_idx);
        }
    }

    注:状态转移方程 dp[i] = (dp[i-1]>=0) ? (dp[i-1]+a[i]) : (a[i])); 和 dp[i] = (dp[i-1]>=0) ? (dp[i-1]+a[i]) : (a[i])); 是有区别的。

  • 相关阅读:
    中台微服务了,那前端如何进行架构设计?
    单体架构&微服务架构&中台服务架构
    SpringCloud oauth2 jwt gateway demo
    SpringCloud-技术专区-认证服务操作
    SpringBoot集成SpringSecurity+CAS
    内核空间与用户空间的通信方式
    函数调用的细节实现
    Kmalloc可以申请的最大内存
    内核调试和系统调用劫持
    stm32最小系统制作(原理图,PCB图,焊接等)
  • 原文地址:https://www.cnblogs.com/dilthey/p/6804182.html
Copyright © 2011-2022 走看看