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. ^_^
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 3Sample Output
6 8Hint
Huge input, scanf and dynamic programming is recommended.
dp[i][j]表示在有i段子序列的时候,前j个元素的最大和
dp[i][j]=max(dp[i][j-1]+a[j],max(dp[i-1][k])+a[j])要么是直接加入第i段的和,要么是令开一段
这里有时间和空间的复杂度问题一定要注意,这里maxx不仅是求出当前的最大值,其实还充当了一个临时变量的作用,因为当我们使用了pre[j-1]的时候,那么pre[j-1]是不是就没有用处了,所以我们直接将maxx的值赋值覆盖,然后maxx其实更新的是这时候的最大值,这就是和max(dp[i-1][k])相当,因为这是在第i段时候前j个元素的最大值,那么我们在第i+1段的时候,去使用它那么就是对的。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
int dp[1000009];
int a[1000009];
int pre[1000009];
int main()
{
int n,m,i,j,k,maxx;
while(~scanf("%d%d",&m,&n))
{
memset(dp,0,sizeof(dp));
memset(pre,0,sizeof(pre));
for(i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
//dp[i][j]表示在前j个元素,取i段情况
//分两种情况,是第i组接在前面,还是自成一段
for(i=1; i<=m; i++)
{
maxx=-99999999;
for(j=i; j<=n; j++)
{
dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);
//dp[j-1]+a[j]相当于dp[i][j-1]+a[j]在后面继续接
//pre[j-1]+a[j]相当于max(dp[i-1][k])+a[j],即自成一段
pre[j-1]=maxx;
maxx=max(dp[j],maxx);
//pre[j-1]也就是在k=(i,j)情况下,dp[i-1][k]的最大值,这样降低时空复杂度
}
}
printf("%d\n",maxx);
}
}