Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 44725 Accepted Submission(s): 16212
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(极光炫影)
最大m段字段和
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define ll long long
const int N=1e6+10;
/*
1.找出最优解的性质,刻画其结构特征
dp(i,j) 表示前j个数(包含第j个数),分成i段的最大字段和
这里将dp(i,j) 表示成包含第j个数(关键得如何想到,可能做多了就会了)
这第j个数有两种情况:
一种是独立成为第i段
另一种是与前面的连在一起成为第i段
这样递推公式就比较好写了
dp(i,j) = max( dp(i-1,k)+a[j],dp(i,j-1)+ a[j] ) k=i-1..j-1
由于包含第j个数,那么dp(m,n) 就不一定是最优解,最优解还得遍历dp(m,1..n)
mx(i,j) 存的是max(dp(i,1..j)
递推公式改为:
dp(i,j)=max(mx(i-1,j)+a[j],dp(i,j-1)+a[j])
2.递推公式
dp(i,j) = max( dp(i-1,k)+a[j],dp(i,j-1)+ a[j] ) k=i-1..j-1
利用mx数组后的
dp(i,j)=max(mx(i-1,j)+a[j],dp(i,j-1)+a[j])
3. 自底向上的计算最优解
先遍历段数由小到大
遍历j=i..n
4.优化
由于此题开二维存不下,
根据数据更新时的特征,每次只需要上一步的状态,可以将二维化为一维
dp(j)=max(mx(j-1)+a[j],dp(j-1)+a[j])
*/
ll dp[N];
ll mx[N];
int a[N];
int main()
{
int m,n;
while(~scanf("%d%d",&m,&n))
{
memset(dp,0,sizeof(dp));
memset(mx,0,sizeof(mx));
for(int i=0;i<n;i++)
scanf("%d",&a[i+1]);
ll mas;
for(int i=1;i<=m;i++)
{
dp[i]=max(dp[i-1],mx[i-1])+a[i];
mas=dp[i];
for(int j=i+1;j<=n;j++)
{
dp[j]=max(dp[j-1],mx[j-1])+a[j];
mx[j-1]=mas;
mas=max(mas,dp[j]);
}
}
cout<<mas<<endl;
}
return 0;
}