HDU--dp练习--1004--Max sum

来源:互联网 发布:系统之家数据恢复 编辑:程序博客网 时间:2024/06/03 19:34

题目:

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.<br>
 

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).<br>
 

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.<br>
 

Sample Input
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 
题目大意:

求最大连续子段和,并求其起止位置。

解题思路:

本身求最大连续子段和不难。

需要在每一步都与当前最大和进行比较,然后记录其起止位置。

源代码:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,m,i,dp[100005],max2,num[100005],maxl,maxr;//用max2记录最大子段和
    cin >> n;
    for (int t = 1; t <= n; t++)
    {
        cin >> m;
        memset(dp,0,sizeof(dp));
        memset(num,0,sizeof(num));
        dp[0] = 0;
        max2 = -999999999;//因为可能均为负数,所以max2设置最小值
        int flag = 1;
        for (i = 1; i <= m; i++)
        {
            cin >> num[i];
            dp[i] = dp[i - 1] + num[i];
            if (dp[i] > max2)//比较过程中判断,并更新其起止位置。
            {
                max2 = dp[i];
                maxl = flag;
                maxr = i;
            }
            if (dp[i] < 0)
            {
                dp[i] = 0;
                flag = i + 1;
            }
        }
        cout << "Case " << t << ":" << endl << max2 << " " << maxl << " " << maxr << endl;
        if (t != n)
            cout << endl;
    }
    return 0;
}


原创粉丝点击