HDU 1024 Max Sum Plus Plus(DP)

 Problem Description

Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.

Given a consecutive number sequence S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj (1 ≤ i ≤ j ≤ n).

Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx is not allowed).

But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(ix, jx)(1 ≤ x ≤ m) instead. ^_^

Input

Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 ... Sn.
Process to the end of file.

Output

Output the maximal summation described above in one line.

Sample Input

1 3 1 2 3 2 6 -1 4 -2 3 -2 3

Sample Output

6 8

Hint

Huge input, scanf and dynamic programming is recommended.

DP中的两种情况:①将第j个数加入到第i部分,②将第j个数做为第i部分的第一个数。

dp[i][j]表示前j个数分为i个部分的最大和,因数值很大,所以将二维降至一维;mk用于储存当前层的最大值

dp[j] = max(dp[j-1],mk[j-1])+num[j]  <前一种是状态①后一种是状态②>

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 1000010
using namespace std;
int main()
{
    std::ios::sync_with_stdio(false);
    int m, n;
    long long imax;
    long long num[MAXN], dp[MAXN], mk[MAXN];
     //mk用于储存当前层的最大值dp[j]表示前j个数字的最大和
    while(~scanf("%d%d", &m, &n))
    {
        memset(num, 0, sizeof(num));
        for(int i = 1; i <= n; i++)
        {
            scanf("%lld", &num[i]);
        }
        memset(dp, 0, sizeof(dp));
        memset(mk, 0, sizeof(mk));
        for(int i = 1; i <= m; i++)//m长度的序列
        {
            imax = -0x7fffffff; //注意imax的定义!就是因为这里WA了好几次。。
            for(int j = i; j <= n; j++)
            {
                if(i == j)
                    dp[j] = mk[j-1] + num[j];//将第j个数作为第i部分的第一个数字
                else
                    dp[j] = max(mk[j-1], dp[j-1]) + num[j];
                //前者是将第j个数字作为第i部分的第一个数字,后者是插入第i部分
                mk[j-1] = imax;//注意这里更新的是j-1!
                imax = max(imax, dp[j]);
            }
        }
        cout << imax << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/blackmail3/article/details/81275594