Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 20107 Accepted Submission(s): 6638
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. ^_^
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.
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 8HintHuge input, scanf and dynamic programming is recommended.
Author
JGShining(极光炫影)
Recommend
/*
题意:n个数划分为m个集合,求集合最大值
思路:dp[i][j]代表 前i个数划分为j个集合的最大值
那么转移方程 dp[i][j]=max(dp[k][j-1],dp[i-1][j])+a[i]
j-1=<k<=i
这里的j可以滚动来节约空间
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define debug printf("%d\n",bug++)
#define eps 1e-8
typedef __int64 ll;
using namespace std;
#define INF 0x3f3f3f3f
#define N 1000005
ll dp[N][2];
int bug;
int m,n;
int a[N];
int main()
{
int i,j;
// freopen("H:/in.txt","r",stdin);
while(~scanf("%d%d",&m,&n))
{
bug=0;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=0;i<=n;i++)
dp[i][0]=dp[i][1]=-1111111111111;
dp[0][0]=dp[0][1]=0;
int cur=0;
for(i=1;i<=m;i++)
{
dp[i][cur]=dp[i-1][cur^1]+a[i];
ll ma=dp[i-1][cur^1]; //前i-1个数组合成i-1个集合的最大值
for(j=i+1;j<=n;j++)
{
ma=max(dp[j-1][cur^1],ma);
dp[j][cur]=max(ma,dp[j-1][cur])+a[j];
//前j-1个数组合成i-1个集合的最大值 前j-1个组合成i个集合加上这个数
}
cur^=1;
}
ll ans=-1111111111111;
cur^=1;
for(i=m;i<=n;i++)
if(dp[i][cur]>ans) ans=dp[i][cur];
printf("%I64d\n",ans);
}
return 0;
}