DP第三题 hdu 1024 Max Sum Plus Plus

Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36771 Accepted Submission(s): 13114

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.

转载:https://blog.csdn.net/u013761036/article/details/39804595
感觉这个分析的比较好
这里写图片描述

dp[i][j]表示的是第j个数字在第i个子序列时的当前最优值。
状态是有两个方向转移过来的,一个是将当前j数字作为第i个序列的第一个数字,另一个是当前数字作为第i个序列的第n(n >= 2)个数字;
dp[i][j] = maxx(dp[i][j-1] + num[j] ,maxx(dp[i-1][k]) + num[j]); k是从1到j-1.
利用滚动数组降成一维
mk[]代表maxx(dp[i-1][k]) + num[j])

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 1000005;
int m,n;
int num[N];
LL dp[N];
LL mk[N];

int main()
{
    while(~scanf("%d %d",&m,&n))
    {
        for(int i = 1;i <= n;++i)
        {
            scanf("%d",&num[i]);
        }
        memset(dp,0,sizeof(dp));
        memset(mk,0,sizeof(mk));
        LL MAX = -1;
        for(int i = 1;i <= m;++i)
        {
            MAX = -inf;
            for(int j = i;j <= n;++j)
            {
                if(i == j)
                    //只能作为下一个序列的开始
                    dp[j] = mk[j - 1] + num[j];
                else
                    dp[j] = max(dp[j - 1],mk[j - 1]) + num[j];
                mk[j - 1] = MAX;
                if(MAX < dp[j]) MAX = dp[j];
            }
        }
        printf("%lld\n",MAX);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36386435/article/details/81461630