zoukankan      html  css  js  c++  java
  • hdu1003(最大连续子列和 )

    Max Sum

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


    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
     
    分析:动态规划。考虑数a[i]的决策,有两种情况:1.连续子列a[k]...a[i-1]的和加上a[i],
    2.a[i]为一个新子列的开端,
    令dp[i]为以a[i]结尾的最大连续子列和,那么dp[i]=max(dp[i-1]+a[i],a[i]);
    化简即if(dp[i-1]<0) dp[i]=a[i];else dp[i]=dp[i-1]+a[i];
     
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int a[200000];
    int dp[200000];
    int main()
    {
        int T,N,cas=0;
        scanf("%d",&T);
        while(T--)
        {
            if(cas) printf("
    ");
            scanf("%d",&N);
            for(int i=0;i<N;i++) scanf("%d",&a[i]);
            memset(dp,0,sizeof(dp));
            dp[0]=a[0];
            int ans=a[0],l=0,r=0,cur=0;
            for(int i=1;i<N;i++)
            {
                if(dp[i-1]<0) {cur=i;dp[i]=a[i];}
                else dp[i]=dp[i-1]+a[i];
                if(ans<dp[i])
                {
                    l=cur;
                    ans=dp[i];
                    r=i;
                }
            }
            printf("Case %d:
    %d %d %d
    ",++cas,ans,l+1,r+1);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    How to function call using 'this' inside forEach loop
    jquery.validate.unobtrusive not working with dynamic injected elements
    Difference between jQuery.extend and jQuery.fn.extend?
    Methods, Computed, and Watchers in Vue.js
    Caution using watchers for objects in Vue
    How to Watch Deep Data Structures in Vue (Arrays and Objects)
    Page: DOMContentLoaded, load, beforeunload, unload
    linux bridge
    linux bridge
    EVE-NG网卡桥接
  • 原文地址:https://www.cnblogs.com/ACRykl/p/8289352.html
Copyright © 2011-2022 走看看