HDOJ1024——Max Sum Plus Plus(好题)

HDOJ1024——Max Sum Plus Plus(好题)

问题描述

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. ^_^

给出一个序列,从中抽取m个连续子序列,求m个连续子序列的和的最大值。


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

问题分析

问题是求从在一个序列中提取m个连续子序列,这m个连续子序列的最大和。

1.基本思路:

首先,定义数组num[n],dp[m][n].
num[n]用来存储n个整数组成的序列.
dp[i][j]用来表示由前 j项得到的含i个字段的最大值,且最后一个字段以num[j]项结尾。仔细想想,我们可以知道:
$dp[i][j]=max(dp[i][j-1]+num[j],dp(i-1,t)+num[j])$ 其中1 <= t < j
(因为必须是以 num[j] 结尾的,所以num[j]一定属于最后一个子段,即要么自己独立成一个子段,要么与前边以num[j-1]结尾的子段联合)
所求的最后结果为 max( dp[m][j] ) 其中1<=j<=n.

2.优化算法

因为状态转移方程为
$dp[i][j]=max(dp[i][j-1]+num[j],dp(i-1,t)+num[j])$
考虑到每次求dp[i][j]都需要获得dp[i][j-1]和dp[i-1][t]的数据,而这些数据在上一次循环中都有出现。可以使用一维数组来保存之前的结果。
定义cur[j],记录当前循环中的最优解,即$dp[i][j-1] + num[j]$需要使用的数据
定义pre[j],记录上层循环中,小于等于j的最大解,即$dp[i-1][t] + num[j]$
注意pre[j]记录的是上一层循环(当前层为i层,上一层为i-1层)中,小于等于j的所有解中最大的那个值。换句话说,记录的是$maxn(dp[i-1][t]) (1 <= t <= j)$
这样,状态转移方程就变成了$cur[j] = maxn(cur[j-1],pre[j-1])$
时空复杂度都有所降低

$$
1
$$

$$ test $$

$$ 1+2 $$

$ 12 $

$
3
$

代码实现

#include<stdio.h>
#include<string.h>
#define MAXN 1000000 + 10
#define MINN -1000000001
int cur[MAXN];
int pre[MAXN];  //pre记录上一次循环时的最大值
int num[MAXN];

int maxn(int a,int b){return a>=b?a:b;}
int main()
{
    int m,n,i,j,max;
    while(scanf("%d%d",&m,&n) != EOF)
    {
        memset(cur,0,sizeof(cur));
        memset(pre,0,sizeof(pre));
        for(i=1;i<=n;i++)
        {
            scanf("%d",&num[i]);
        }
        for(i=1;i<=m;i++)
        {
            max = MINN;
            for(j=i;j<=n;j++)
            {
                cur[j] = maxn(cur[j-1] + num[j],pre[j-1] + num[j]);  //先取pre再赋值的含义:先取上一层循环时pre的值,再更新pre的值
                pre[j-1] = max;  //更新为本次循环的最大值,在下一次循环中会使用到
                if(max < cur[j])  max = cur[j];
            }
            pre[j-1] = max; //此时j-1为数列中的最后一个数字
        }
        printf("%d\n",max);
    }
}
... ... ...