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
这个题的意思是找m个不相交的区间,求他们的最大和,这个题,如果我们用二维的数组进行dp,dp[i][j]=max(dp[i][j-1]+num[j],dp(i-1,t)+num[j]) 其中i-1<=t<=j-1,其中,dp[i][j]表示以a[j]结尾而有i个间的最大和,但是这就提高了空间复杂度,怎么办呢,注意,这里状态转移的时候既有dp[i]的数组,又有dp[i-1]的数组,这导致我们dp的时候不能像背包一样只开一个一维数组,因为后面的状态必定要覆盖掉前面的状态,这样我们只能另外找一个数组,把i-1的状态存起来,这个和做划分数的一维数组做法是一模一样的!!注意状态转移的顺序,pre表示i-1的状态,为什么之前背包可以用一维数组做,就是因为状态转移的顺序决定的!!!
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int a[1000004];
int dp[1000004];
int pre[1000004];
int main()
{
int n,m;
while(~scanf("%d%d",&m,&n))
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
dp[i]=pre[i]=0;
}
int res=0;
dp[0]=pre[0]=0;
for(int i=1;i<=m;i++)
{
res=-100000000;
for(int j=i;j<=n;j++)
{
dp[j]=max(dp[j-1],pre[j-1])+a[j];
pre[j-1]=res;
res=max(dp[j],res);
}
}
cout<<res<<endl;
}
}
hdu 1024
原文:https://www.cnblogs.com/coolwx/p/11173543.html