hdu 1024(滚动数组+动态规划)

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23697    Accepted Submission(s): 8094


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
 
没做出来。。只能想到二维的,滚动数组果然厉害.

题意:n个数字分成m段的最大和
分析:dp[i][j] 代表以a[j]结尾的前j个数字被分成 i 段得到的最大和
可以得到: 1.如果a[j]单独成段 dp[i][j] = dp[i-1][k] + a[j] 其中 1<=k<j 意思是前1- k 个数字组成了i-1段.
             2.如果a[j]并入第i段 那么dp[i][j]=dp[i][j-1]+a[j] 分析可得 dp[i][j] = max(1,2)
但是这题的条件是不允许这样做的 ,首先枚举 i , j ,k 的时间复杂度是 O(n^3) dp数组的空间要 O(n^2),而数据量已经到达了 1000000 显然不允许.于是,这里就要用一个新的思想了:滚动数组.
我们可以看到dp[i][j]只和是否包含a[j]相关,所以这里我们可以用两个一维数组存当前状态与前一个状态.
新的状态: dp[j]表示以a[j]结尾的前i段的最大和,pre[j]表示前j个数组成前i段的最大和,不一定包括a[j]
dp[j] = max(dp[j-1]+a[j],pre[j-1]+a[j])

/**题意:n个数字分成m段的最大和*/
///分析:dp[i][j] 代表以a[j]结尾的前j个数字被分成 i 段得到的最大和
///可以得到: 1.如果a[j]单独成段 dp[i][j] = dp[i-1][k] + a[j] 其中 1<=k<j 意思是前1- k 个数字组成了i-1段.
///          2.如果a[j]并入第i段 那么dp[i][j]=dp[i][j-1]+a[j] 分析可得 dp[i][j] = max(1,2)
///但是这题的条件是不允许这样做的 ,首先枚举 i , j ,k 的时间复杂度是 O(n^3) dp数组的空间要 O(n^2),而数据量已经
///到达了 1000000 显然不允许.于是,这里就要用一个新的思想了:滚动数组.
///我们可以看到dp[i][j]只和是否包含a[j]相关,所以这里我们可以用两个一维数组存当前状态与前一个状态.
///新的状态: dp[j]表示以a[j]结尾的前i段的最大和,pre[j]表示前j个数组成前i段的最大和,不一定包括a[j]
///dp[j] = max(dp[j-1]+a[j],pre[j-1]+a[j])
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int N = 1000005;
int a[N];
int dp[N];
int pre[N];
int main()
{
    int m,n;
    while(scanf("%d%d",&m,&n)!=EOF){
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            dp[i]=pre[i]=0;
        }
        dp[0]=pre[0]=0;
        int mam;
        for(int i=1;i<=m;i++) {///枚举每一段
            mam = -0x7fffffff;
            for(int j=i;j<=n;j++){
                dp[j] = max(dp[j-1]+a[j],pre[j-1]+a[j]);
                pre[j-1] = mam;  ///表示前 j-1 个数组成i段能够表示的最大和
                mam=max(dp[j],mam);
            }
        }
        printf("%d
",mam);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/liyinggang/p/5391312.html