HDU1003 Max Sum 解题报告

Posted velscode

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU1003 Max Sum 解题报告相关的知识,希望对你有一定的参考价值。

目录

题目信息

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.

给出一个序列a[1],a[2],a[3]......a[n],你的任务是计算子序列的最大和,例如,对于(6,-1,5,4,-7),最大和是这个子序列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).

第一行包括一个整数T(1<=T<=20),代表测试用例的数量。接下来的T行,每行开始于一个数N(1<=N<=100000),然后跟着N个数,所有的整数都在 -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.

对于每个测试用例,你应该输出两行。第一行是Case #:,#代表测试用例的序号。第二行包括三个数,序列最大和,还有这个子序列的开始和结束坐标。如果有超过一个以上的结果,输出第一个即可。在两个用例之间输出一个空行。

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

题解

思路

典型的动态规划问题,可参见【最长子序列和】。
本题要求输出满足条件的子序列区间,一个for循环就可以搞定

源代码

//HDU 1003 VELSCODE VER1.0
#include <iostream>

using namespace std;

int T,N,max1[20],L[20],R[20];

int A[100000],DP[100000];

int main()
{
    //input
    scanf("%d",&T);
    for( int t=0;t<T;t++ )
    {
        scanf("%d",&N);
        for( int i = 0; i < N; i++ )
        {
            scanf("%d",&A[i]);
        }
        
        //dp
        DP[0] = A[0];
        
        for(int i=1;i<N;i++)
        {
            if( A[i] > DP[i-1]+A[i] )
            {
                DP[i] =  A[i];
            }
            else //A[i] < DP[i-1]+A[i] 
            {
                DP[i] = DP[i-1]+A[i];
            }
        }
        
        //寻找最大值 
        int pos = 0;
        
        max1[t] = DP[0];
            
        for(int i=0;i<N;i++ )
        {
            if( max1[t] < DP[i] )
            {
                max1[t] = DP[i];
                pos = i;
            }
        }
        
        //寻找子序列左右坐标 
        R[t] = pos;
        L[t] = pos; 
        
        for( int i = pos - 1 ; i >= 0 ;i--  )
        {
            if( DP[i] >= 0 )
            {
                L[t] = i;
            }
            else 
                break;
        }
    }
    
    //output 
    for( int i = 0; i < T; i++ )
    {
        printf("Case %d:
",i+1);
        printf("%d %d %d
",max1[i],L[i]+1,R[i]+1);
        if( i != T-1 )
        printf("
");
    }

}





以上是关于HDU1003 Max Sum 解题报告的主要内容,如果未能解决你的问题,请参考以下文章

hdu1003 Max Sum最大连续子序列之和

HDU1003 Max Sum 题解 动态规划 最大字段和扩展

HDU 1003 - Max Sum

MAX SUM(HDU_1003——dp)

hdu-1003 Max Sum

HDU1003:Max Sum