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组
当考虑到第j个数时有两种决策
1 第j个数加入第i组:dp[i][j]=dp[i][j-1]+a[j]
2 第j个数单独成组:dp[i][j]=max(dp[i-1][k]+a[j]) 0<k<j
两种情况去最大值即可!!!
时间复杂度 n^3. n<=1000000. 会超时,继续优化。
max( dp[i-1][k] ) 是上一组 0…j-1 的最大值。在每次计算dp[i][j]的时候记录下前j个
的最大值,用数组保存下来 ,下次计算的时候可以用,时间复杂度变为 n^2.
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000010
#define inf 0x3f3f3f3f
int a[maxn];
int dp[maxn];
int dpa[maxn];
int main()
{
int n,m;
int maxnn;
while(~scanf("%d%d",&m,&n))
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
dp[i]=0;
dpa[i]=0;
}
dp[0]=0;
dpa[0]=0;
for(int i=1;i<=m;i++)
{
maxnn=-inf;
for(int j=i;j<=n;j++)
{
dp[j]=max(dp[j-1],dpa[j-1])+a[j];
dpa[j-1]=maxnn;
maxnn=max(dp[j],maxnn);
}
}
printf("%d\n",maxnn);
}
return 0;
}