Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25894 Accepted Submission(s): 9004
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(极光炫影)
Recommend
题意:
给你n个数,取出m段不向交的数,求m段的数的和的最大值?
分析:
由于是动态规划专题,所以我就可以直接往动态规划想了。
那么dp[i][j]要表示什么呢?
由于题目中只有两个变量n,m,所以和快就可以想到dp[i][j]表示在前j个数中取i段的最大值。
现在想想前j-1个数和第j个数的关系?
(1)如果我们不取第j个数,那么dp[i][j]=dp[i][j-1],由于dp[i][j-1]我们已经求出了所以不用再考虑。
(2)第j个数一定取。有两种情况,
1:第j个数和前j-1个数的最后一段和在一起组成最后一段:dp[i][j] = dp[i][j-1] + a[j];
2:第j个数单独是一段,在前j-1个数中取i-1段。dp[i][j]=dp[i-1][j-1] + a[j];
所以dp[i][j] = max(dp[i][j-1]+ a[j] , dp[i-1][j-1] + a[j])。
由于n<=1000000 很大,所以要用滚动数组优化。 其中数组mmax[j-1] = dp[i-1][j-1]。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 1000005;
const int INF = -99999999;
int dp[maxn],a[maxn];
int mmax[maxn];
int main()
{
int m,n;
while(scanf("%d%d",&m,&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
dp[i] = 0;
mmax[i] = 0;
}
dp[0] = 0;
mmax[0] = 0;
int ans = INF;
for(int i=1;i<=m;i++)
{
ans = INF;
for(int j=i;j<=n;j++)
{
dp[j] = max(dp[j-1]+a[j],mmax[j-1]+a[j]);
mmax[j-1] = ans;
ans = max(ans,dp[j]);
}
}
printf("%d\n",ans);
}
return 0;
}