Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31033 Accepted Submission(s): 10942
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.
Author
JGShining(极光炫影)
题目大意:给出n个数的序列,问从中选择m个不相交的区间,区间和最大是多少。
解题思路:动态规划,这种类型的dp一般设为前 i 个数,且以 i 结尾的,有 j 种 blabla 的最小值(最大值等)
由于 n 有 106 ,所以开两维是不行的,一般是先行后列填表,所以根据状态转移方程(见代码),可以发现行可以压缩,又出现了连续区间的最大值,所以考虑前缀和优化(可能是这个吧,反正是要优化~),记录下那个最大值,扫完一行后记得更新,还有就是初始化要想清楚。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const int MAXN=1e6+5;
int a[MAXN];
LL dp[MAXN];
LL colmax[MAXN];
int m,n;
//dp[i][j]:前i个数且选择第i个数,分成j组的最大值
//dp[i][j]=max(dp[i-1][j]+a[i],max(dp[1][j-1],...,dp[i-1][j-1])+a[i]);
/*
1 2 3 ... m
1
2
.
.
.
n
行可以压缩~
*/
void init()
{
for(int j=1;j<=m;j++)
{
colmax[j]=-INF;dp[j]=-INF;
}
colmax[0]=0;dp[0]=0;
}
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
init();
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
LL ans=-INF;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
dp[j]=max(dp[j]+a[i],colmax[j-1]+a[i]);
}
for(int j=1;j<=m;j++)
{
colmax[j]=max(colmax[j],dp[j]);
}
ans=max(ans,dp[m]);
}
printf("%lld\n",ans );
}
return 0;
}
/*
1 3 1 2 3
2 6 -1 4 -2 3 -2 3
6
8
*/