1. 程式人生 > >HDU1003 Max Sum 解題報告

HDU1003 Max Sum 解題報告

can sam all ive 滿足 ble rip 用例 NPU

目錄

  • 題目信息
    • Problem Description
    • Input
    • Output
    • Sample Input
    • Sample Output
  • 題解
    • 思路
  • 源代碼

題目信息

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:\n",i+1);
        printf("%d %d %d\n",max1[i],L[i]+1,R[i]+1);
        if( i != T-1 )
        printf("\n");
    }

}

HDU1003 Max Sum 解題報告