Max Sum Plus Plus
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
题意:
在给定数组中找出m段不重叠的区间,对这些区间的值求和,使得和最大。
题解
d[i][j]:前i个数选j对,并且以i结尾
d[i][j]=max{ (max(d[k][j-1])其中(j-1<=k<=i-1)) , d[i-1][j] }+ a[i];
很明显,空间存不下
我们只需要用到上一层前i个的最大值,所以不需要枚举k,用一个premax数组保存下信息,并不断更新即可。这就让我们使用滚动数组的思想优化空间具备了可行性.
第一种优化方法:优化第一层
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5, inf = 1e9 + 7;
int a[maxn], dp[maxn], premax[maxn];
/*
前i个数选j对,并且以i结尾
d[i][j]=max(max(d[k][j-1],(j-1<=k<=i-1))+a[j],d[i-1][j]+a[i])
premax[i]:选j-1对时,前i个数结尾的最大值
记录选j-1对的最大值,先枚举j,再枚举i,
int nowmax;
for(j:1~n)
nowmax=-inf;
for(i:j~n)
d[j]=max(premax[i-1],d[j])+a[i];
premax[i-1]=nowmax;
nowmax=max(d[j],nowmax);
*/
int main()
{
int n, m, temp;
while (cin >> m >> n)
{
for (int i = 1; i <= n; i++)
cin >> a[i];
fill(dp, dp + n + 1, -inf);//dp[i][i]为全选,所以置为无穷大,当i=j时,就会全选
memset(premax, 0, sizeof(premax));
int nowmax;
for (int j = 1; j <= m; j++)
{
nowmax = -inf;
for (int i = j; i <= n; i++)
{
dp[j] = max(dp[j], premax[i - 1]) + a[i];
premax[i - 1] = nowmax;
nowmax = max(nowmax, dp[j]);
}
}
cout << nowmax << endl;
}
return 0;
}
第二种优化方法:优化第二层
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5, inf = 1e9 + 7;
int a[maxn], dp[maxn], premax[maxn];
/*
前i个数选j对,并且以i结尾
d[i][j]=max((max(d[k][j-1])(j-1<=k<=i-1)),d[i-1][j])+a[i];
premax[i]:选j-1对时,前i个数结尾的最大值
记录选j-1对的最大值,先枚举j,再枚举i,
int nowmax;
for(j:1~n)
nowmax=-inf;
for(i:j~n)
d[i]=max(premax[i-1],d[i-1])+a[i];
premax[i-1]=nowmax;
nowmax=max(d[i],nowmax);
*/
int main()
{
int n, m, temp;
while (cin >> m >> n)
{
for (int i = 1; i <= n; i++)
cin >> a[i];
dp[0]=0;//每次用到的都是dp[i-1]来更新dp[i],所以其实无需初始化
memset(premax, 0, sizeof(premax));//前i-1个数选0对
int nowmax;
for (int j = 1; j <= m; j++)
{
nowmax = -inf;
for (int i = j; i <= n; i++)
{
dp[i] = max(dp[i-1], premax[i - 1]) + a[i];
premax[i - 1] = nowmax;
nowmax = max(nowmax, dp[i]);
}
}
cout << nowmax << endl;
}
return 0;
}