hdu 1024 最大M子段和
标签:
acm杂谈 |
Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others)Total Submission(s): 4521
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 8
Hint
Huge input, scanf and dynamic programming is recommended.Author
JGShining(极光炫影)
思路:
dp[i][j]表示前j个元素分成i段的最优解,同时这个最优解是由a[j]元素结束的。
转移方程是dp[i][j]=max{f[i][j-1]+a[j],f[i-1][k]+a[j],(i-1<=k<j)}
(i<=j<=n-m+i)
其中j的上下界的确定比较麻烦。现在分别解释上界和下界:
上界:dp[i][j]中,如果j=i-1,意思就是在前面i-1个元素中分成i段,这个是不可能实现的。
下界:如果m=n=4,这时dp[2][4]求出来了,意思是前面的四个元素分成了两段,当是还有两段要分,
这是其中一个特例的状态转移表 m=4,n=6 ,-1 4 -2 3 -2 3
没有填的说明不用算。
很显然dp[i][i]=dp[i-1][i-1]+a[i],
所以对角线上面有:
http://s6/middle/677a3eb30745bec2b1de5&6901024 最大M子段和" TITLE="hdu 1024 最大M子段和" />
现在演示一下转移过程。如何求下图的框中的元素的值
现在演示一下转移过程。如何求下图的框中的元素的值
http://s5/middle/677a3eb348b9742f2ad94&6901024 最大M子段和" TITLE="hdu 1024 最大M子段和" />
由下面涂色的元素的最大值加上a[3]=-2求的如下图
由下面涂色的元素的最大值加上a[3]=-2求的如下图
http://s3/middle/677a3eb348b974f98bc32&6901024 最大M子段和" TITLE="hdu 1024 最大M子段和" />
最大的是4,所以4+(-2)=2;框中填2;
最大的是4,所以4+(-2)=2;框中填2;
假如框中的元素是dp[i][j],画圈的元素表示的是,左边那个是dp[i][j-1],上面的几个是dp[i-1][k](i-1<=k<j)}
,这个就是上面的转移方程的表格表示法。
其他细节如果理解上面的内容,就可以优化了
#include<stdio.h>
__int64 dp[2][1000001];
__int64 a[1000001];
__int64 b[1000001];
__int64 res;
int n,m;
__int64 Max(__int64 x,__int64 y)
{
}
int main()
{
//
}

加载中…