hdu1003 Max Sum [sum of the largest consecutive subsequences]

Question link: https://vjudge.net/problem/HDU-1003

 

The gist of the title:
Given a sequence, find the sum of the largest consecutive subsequences, and give the start and end points of this subsequence.

Problem- solving idea:
There are actually many ways to solve the problem of the sum of the longest continuous subsequences. Here, the dynamic programming with time complexity of O(n) is used to solve it.

The idea is very clear. The dp array is used to represent the sum of the largest consecutive subsequences of the first i items. If dp[i-1]>=0, then dp[i] plus dp[i-1] can make dp[i] ] increases; if dp[i-1]<0, then take dp[i] as the starting point again, and the starting point is updated.

 

 

#include <cstdio>

intmain ()
{
    int t, n, i, j, cas = 0;
    scanf("%d", &t);
    while (t--)
    {
        int dp[ 100010 ];          // The dp array represents the sum of the largest consecutive subsequences ending in i 
        scanf( " %d " , & n);
         for (i = 1 ; i <= n; i++)scanf( " % d " , & dp[i]);
        dp[0] = -1;
        int max = -0x3f3f3f3f;
        int s=1,start=1, e;
        for (i = 1; i <= n; i++)
        {
            if (dp[i - 1 ] >= 0 )dp[i] = dp[i - 1 ] + dp[i];        // If dp[i-1]>=0, the i-th number is directly on the original basis Add up 
            else s = i;               // Otherwise, re-add with the i-th number as the starting point 
            if (max < dp[i])
            {
                max = dp[i];
                e = i;                // Record the end point at this time 
                start = s;           // Record the start point at this time, be careful not to confuse start with s, s is just the start point of each segment, and start is the current encounter contiguous subsequence and largest starting point 
            }
        }
        printf("Case %d:\n", ++cas);
        printf("%d %d %d\n", max, start, e);
        if (t)printf("\n");
    }
    return 0;
}

 

 

2018-04-30

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325165597&siteId=291194637