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.
代码
//#pragma GCC optimize(3)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<climits>
#include<queue>
#include<set>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)<(y)?(x):(y))
#define swap(x,y) (x^=y,y^=x,x^=y)
typedef long long ll;
using namespace std;
template<typename T>inline void read(T &x)
{
x=0;
T f=1;
char c=getchar();
for(; c<'0'||c>'9'; c=getchar()) if(c=='-') f=-1;
for(; c>='0'&&c<='9'; c=getchar()) x=(x<<1)+(x<<3)+(c&15);
if(f==-1)
x=-x;
}
template<typename T>inline void print(T x)
{
if(x<0) putchar('-'),x*=-1;
if(x>=10) print(x/10);
putchar(x%10+'0');
}
int n,m;
const int N=1e6+7;
int pre[N];
int dp[N];
int a[N];
int main()
{
while(~scanf("%d%d",&m,&n))
{
memset(dp,0,sizeof(dp));
memset(pre,0,sizeof(pre));
for(int i=1; i<=n; i++)
{
read(a[i]);
}
int maxn=-INT_MAX;
for(int i=1; i<=m; i++)
{
maxn=-INT_MAX;
for(int j=i; j<=n; j++)
{
dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);
pre[j-1]=maxn; //这样的记录是为了保证pre[j-1]+a[j]中的pre[j-1]的值是上一层的,而不是本层的,防止本次的pre覆盖上一层的。
maxn=max(dp[j],maxn); //同时也更新本层的pre值。
}
}
print(maxn);
puts("");
}
return 0;
}
思路
最大m字段和问题。
转移方程 dp[i][j]=max(dp[i][j-1]+a[j], max(dp[i-1][k])+a[j]);
dp[i][j-1]+a[j]表示的是前j-1分成i组,第j个必须放在前一组里面。
max( dp[i-1][k] ) + a[j] )表示的前(0<k<j)分成i-1组,第j个单独分成一组
由于数据量太大并且与i-1项有关,故开一个数组保存前一组的最大值即可。