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 S 1, S 2, S 3, S 4 … S x, … S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + … + S j (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(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + … + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x 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(i x, j x)(1 ≤ x ≤ m) instead. _
Input
Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 … S n.
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

Hint
Huge input, scanf and dynamic programming is recommended.

题意:给n个数,将其分为m部分,各部分之间不能有交叉重叠,求最大子段和

思路
dp[i][j]表示将前j个数分为i部分(以a[j]为结尾)的最大子段和,则
dp[i][j] = max(dp[i][j-1] + a[j], dp[i-1][k] + a[j]) i-1<=k<=j-1
前者是将第j个数加入到第i部分,后者是将第j个数做为第i部分的第一个数。

分析
因为题目n值范围过大,显然二维数组不行,所以要将其降低至一维。
因为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])

注意pre[]应在哪里更新

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+5;
int a[maxn],pre[maxn],dp[maxn];
int main(){
	int m,n;
	while(~scanf("%d%d",&m,&n)){
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		memset(pre,0,sizeof(pre));
		memset(dp,0,sizeof(dp));
		int maxx;
		for(int i=1;i<=m;i++){
			maxx=-999999999;
			for(int j=i;j<=n;j++){
				dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);//前者是将第j个数加到第i部分,后者是将第j个数作为第i部分的第一个数 
				pre[j-1]=maxx;//为i+1做准备 
				maxx=max(maxx,dp[j]);//保存前j个数,段数为i时的最大值 
			}
		}
		printf("%d\n",maxx);
	}
	return 0;
}