Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 47232 Accepted Submission(s): 17198
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
Hint
Huge input, scanf and dynamic programming is recommended.
思路:
把一个数组分为m段,那么 dp[i][j]表示前j个数分为i组,
则第一种情况为j与其他元素在最后一组里:dp[i][j-1]+a[j],第二种情况为j单独一组:dp[i-1][k]+a[j],k=i-1,…,j-1;前面的j-1个数一些可以不分在组里,所以最小为i-1个组,在这些里面找到最大的.
所以dp[i][j]=max(dp[i][j-1],max(dp[i-1][i-1]~dp[i-1][j-1]))+a[j].
但是题中的n太大,m不知道,这样的话会超时,也会爆内存,所以要优化。
我们发现这一层的状态只依赖上一层的状态,这样可以优化内存,但是时间没有优化,接下来我们可以将dp[i-1][i-1]~dp[i-1][j-1]这一段的值每次都保存在一个数组里pre[],pre[j-1]表示在第j-1个数这里的最大的值,这样就可以优化时间了。
对于下面的pre的由来,我们可以发现i=1的时候去算dp[i-1][k]的时候,从pre[]里得来的其实是0,因为dp[0][k]=0,分为0组的值为0,并且这时候我们就在算dp[1][k]的值存在pre里面,以便i=2的时候用。
假如n=4,i=2,那么我们要算dp[1][1]–dp[1][3],在i=1时我们就求得了pre[1]-pre[3],那么在i=2,j=2的时候,我们就用pre[j-1]去比较了。
并且最后结果应该是tmp,而不是dp[n],因为我们最后tmp=max(dp[j],tmp)的时候进行了最后的比较。
完整代码(有注释)
注:/**/ 部分注释为展示具体过程
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1e6+5;
int dp[maxn];//当前的最大值:dp[j]=前j个数分成i组的最大值
int a[maxn];//存放输入数据
int pre[maxn];//上一层的最大值:pre[j]=前j个数分成i-1组的最大值
int tmp= 0;//中间变量,记录最大值
const int INF = 0x3f3f3f3f;
int main()
{
int n, m;
while (~scanf("%d%d", &m, &n)){
for (int i = 1; i <= n; i++){
scanf("%d", &a[i]);
dp[i] = 0;
pre[i] = 0;
}
for (int i = 1; i <= m; i++){
tmp = -INF;
/*for(int j=i;j>=1;j--)
cout<<"\t";*/
for (int j = i; j <= n; j++){//前i个直接分成i组
//前者:a[j]加入这一层(i组)分组
//后者:从上一层(i-1组)选最大值,a[j]独立
dp[j] = max(dp[j - 1] + a[j], pre[j - 1] + a[j]);
pre[j - 1] = tmp;//用完后就更新,-INF这个值永远不会被用到,因为每层都会错开
//且每次更新不影响这一层的pre,因为用过才更新
tmp = max(tmp, dp[j]);//保持最大值,当分为一组时,tmp值退化为最大上升子序列
/*cout<<dp[j]<<","<<tmp<<"\t";*/
}
/*cout<<endl;*/
}
cout << tmp << endl;
}
}