HDU 1003 - Max Sum(动态规划 & 找最大价值连续子串)

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

题目要求给你一个数字串,从这里面找到一个和最大的子串,这种题目,还是直接用dp来做吧。
用一个结构体来存储一下子串的开始位置和结束位置,还有该子串的价值。因为要求连续子串,那么我们只要关注前一个状态就好了。
如果前一个状态保存的子串价值为负值,那么该点的就自己作为一个子串。因为我们假设前面一个数字构成的子串价值为负值,那么当前数字加上这个负值一定小于该点的值,那么就不如直接让这个点自己作为一个子串,价值会更大。

AC代码:

#include 
#include 
#include 
#include 
#define ll long long
using namespace std;
const int maxn = 1e5 + 5, inf = 0x3f3f3f3f;
ll sum[maxn], a[maxn];

struct node
{
    int s, e;
    ll sum;
    bool operator < (const node& obj) const
    {
        if(sum == obj.sum) return s > obj.s;
        else return sum < obj.sum;
    }
}dp[maxn];

int main()
{
    int t, n;
    scanf("%d", &t);
    for(int test = 1; test <= t; test++)
    {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)    scanf("%lld", &a[i]);
        printf("Case %d:\n", test);
        dp[1].sum = a[1];
        dp[1].s = 1;
        dp[1].e = 1;
        for(int i = 2; i <= n; i++)
        {
            if(dp[i - 1].sum >= 0)
            {
                dp[i].sum = dp[i - 1].sum + a[i];
                dp[i].s = dp[i - 1].s;    dp[i].e = i;
            }
            else
            {
                dp[i].sum = a[i];
                dp[i].s = i;    dp[i].e = i;
            }
        }
        sort(dp + 1, dp + 1 + n);//找出最大的一个
        printf("%lld %d %d\n", dp[n].sum, dp[n].s, dp[n].e);
        if(test != t)   printf("\n");
    }
    return 0;
}

你可能感兴趣的:(动态规划)