hdu 1024 Max Sum Plus Plus(最大m段子序列和)

时间:2022-10-20 18:44:23

Max Sum Plus Plus

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

分析:用dp[i][j]表示前j个数取出i段得到的最大值,那么状态转移方程为dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j]) , i-1<=k<=j-1
也就是说有两种不同的选择:第一个是第j个连在第j-1个所在的段的后面,第二个是第j个为新的一段的第一个数字。

但是如果n^3写的话,分分钟TLE。。而且二维数组也开不了那么大,所以要压缩成一维数组。

因为dp[i-1][t]的值只在计算dp[i][j]的时候用到,那么没有必要保存所有的dp[i][j] for i=1 to m,这样我们可以用一维数组存储。
用pre[j]表示前一个状态中1–j的dp的最大值,就变成 dp[j] = max(dp[j-1] + a[j] ,pre[j-1]+a[j])(具体详见代码)

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define maxn 1000010
const int inf=0x3f3f3f3f;
int dp[maxn],pre[maxn],a[maxn];
int n,m;

int main()
{
while(~scanf("%d%d",&m,&n))
{
memset(dp,0,sizeof(dp));
memset(pre,0,sizeof(pre));
for(int i=1; i<=n; ++i)
scanf("%d",&a[i]);
int maxx;
for(int i=1; i<=m; ++i)
{
maxx=-inf;
for(int j=i; j<=n; ++j)
{
dp[j]=max(dp[j-1],pre[j-1])+a[j];
pre[j-1]=maxx;//为i+1做准备
if(dp[j]>maxx)
maxx=dp[j];//保存前j个段数为i时的最大值
}
}
printf("%d\n",maxx);
}
return 0;
}



总结:这道题n^3的能推出来,但是压缩成一维的却一点也不好写。。
一是对第二个for循环的范围没有把握好,没有想清楚j必须从i开始
二是化成一维时对最终的结果必须从dp[m][1~n]中得出这一点没有控制好
三是对pre[]更新的时间没有想清楚,每一次更新pre[]实际上是为下一个状态做准备,不能影响本次的状态