Max Sum Plus Plus(hdu-1024)
原题描述:
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.
题意:
在n个数中选出m组数, 每组数连续且不能相交, 求出最大的各组数的和
题解:
- 定义v[j]为输入的第j个数
- 然后定义dp[i][j]状态为: 在前j个数中恰好选出以v[j]结尾的i组数的最大和
得出状态转移方程dp[j][j]=max(dp[i][j−1]+a[j],dp[i−1][k]+a[j] (k<j))- 意义为
1:取第j个数归入当前第i组,因为dp[i][j-1]肯定选择了vis[j-1],那么再选择第vis[j]是可以和vis[j-1]并入一组的,不需要开辟新的组。
2:取第j个数记录为新的组.虽然dp[j-1][k](k<j),选择的前i-1组最后一个数字是vis[k] k<j,有可能取到vis[j-1] ,但是这并不妨碍我们将vis[j]单独一组- 显然n^2的复杂度, 不管是空间上有可能无法通过,而且我们发现每次i层的状态至于第i层和第j层有关系,所以我们可以使用滚动数组只记录这两层的数据
- 举一个简单的例子来描述转移方程的dp[i-1][k] 的k为什么是小于j 而不是j-1,一个长度为4的数组分成两个区间,数组数据为2,3,4,5那么分组结果可以是2一组,3,4,5一组,也可以是2,3,4一组,5一组,结果都是14
(该举例是为了让读者明白,虽然取得数可能是连续的,但是却有可能是属于不同的区间,可能例子并不明确,还请见谅)
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 1000100;
int a[MAXN];
int dp[MAXN];
int lastMax[MAXN];
int main() {
int M,N;
while(scanf("%d%d",&M,&N)!=EOF){
memset(lastMax,0,sizeof(lastMax));
memset(dp,0,sizeof(dp));
memset(a,0,sizeof(a));
for(int i=1;i<=N;++i){
scanf("%d",&a[i]);
}
int tmp;
for(int i=1;i<=M;++i){//分成多少组
tmp=-1e9;
for(int j=i;j<=N;++j){
//printf("<j-1: %d %d %d>",j-1,dp[j-1],lastMax[j-1]);
dp[j] = max(dp[j-1],lastMax[j-1])+a[j];
lastMax[j-1]= tmp;//前j-1最大值,留到下一层才用(包含j-1)
tmp = max(tmp,dp[j]);//第m层前j最大值
}
//printf("\n");
}
printf("%d\n",tmp);
}
return 0;
}