HDU

来源:互联网 发布:2017全球华人网络春晚 编辑:程序博客网 时间:2024/05/27 10:44

Max Sum Plus Plus


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 32 6 -1 4 -2 3 -2 3
 

Sample Output
68
Hint
Huge input, scanf and dynamic programming is recommended.
 



题意:求M段的连续子段和的最大和。如样例  -1 4 -2 3 -2 3可以分为  (4)  (3 -2 3),这两段和为8为最大。



解题思路:膜拜前人,他们到底是怎么想到的,看了各种博客,最后加上自己的理解,终于搞懂了。希望以后自己也能独立思考出来。

我们用一个二维数组dp[i][j]表示前j个数分为i段的最大和。

这时就会有转移方程dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j]) (i-1<=k<=j-1)

前者的意思是把a[j]加到当前的子段中,后者的意思是把a[j]作为单独的一段

之所以要k这个变量,是想找出前j个数,只用i-1段时的最大和

因此这里是可以优化的,而且这个优化也是必不可少的,不然会超内存!有的把它叫为滚动数组。

因此转移方程可以优化为dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]),pre为前j个数的最大i-1段连续子段和。详见代码。


#include<iostream>#include<memory.h>#include<string>#include<algorithm>using namespace std;const int MAXN=1000005;int dp[MAXN];//保存最终答案int pre[MAXN];//保存前一个M的答案int a[MAXN];int N,M;int main(){    while(~scanf("%d%d",&M,&N)){        for(int i=1;i<=N;i++)            scanf("%d",&a[i]);        memset(dp,0,sizeof(dp));        memset(pre,0,sizeof(pre));        int ans=-9999999;        for(int i=1;i<=M;i++){            ans=-9999999;            for(int j=i;j<=N;j++){                dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);//更新这次i的答案,相当于dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j]),k为上一次的j                //前者为普通的求最大连续子段和过程,即把这个数字加进去试试,后者为把a[i]当做独立的一段加进去试试,因此要用上次循环(i-1)保存的答案.a[i]占了一段,所以要用上一次。                pre[j-1]=ans;//保存本次i的答案。(不能放在下面的if后面,否则就是最新的答案了,我们要保存的是上次的答案)                if(dp[j]>ans)                    ans=dp[j];            }        }        printf("%d\n",ans);    }    return 0;}







原创粉丝点击