现在的位置: 首页 > 综合 > 正文

HDU 1003 Max sum

2018年04月28日 ⁄ 综合 ⁄ 共 1573字 ⁄ 字号 评论关闭

Max Sum

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


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
 


Author
Ignatius.L
 

解题思路:

这道题,看起来很水,也就是个dp求最大连续子序列的和。。那么只要定义好状态就可以了,dp[i] 表示的是以a[i]为结尾的最大子序列的和。

那么状态转移方程为:dp[i] = max( dp[i-1]+a[i],a[i] )

不说了,直接上代码:

# include<cstdio>
# include<iostream>

using namespace std;

# define MAX 100000

int mat[MAX];

struct node
{
    int l;
    int r;
}seg[MAX];


int main(void)
{
    int n;
    int icase = 0;
    int t;cin>>t;
    while ( t-- )
    {
        icase++;
        cin>>n;
        for ( int i = 1;i <= n;i++ )
        {
            cin>>mat[i];
        }
        seg[1].l = 1;
        seg[1].r = 1;
        for ( int i = 2;i <= n;i++ )
        {
            if ( mat[i] <= mat[i-1]+mat[i] )
            {
                mat[i] = mat[i-1]+mat[i];
                seg[i].l = seg[i-1].l;
                seg[i].r = i;
            }
            else
            {
                seg[i].l = seg[i].r = i;
            }
        }

        int maxID = 1;
        int _max = mat[1];

        for ( int i = 2;i <= n;i++ )
        {
            if ( mat[i] > _max )
            {
                _max = mat[i];
                maxID = i;
            }
        }
        printf("Case %d:\n",icase);

        printf("%d %d %d\n",_max,seg[maxID].l,seg[maxID].r);

        if ( t != 0 )
            cout<<endl;

    }

    return 0;
}

抱歉!评论已关闭.