HDU - 1024 Max Sum Plus Plus(最大M段连续子段和,详细解释)

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 S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (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(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x 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(i x, j x)(1 ≤ x ≤ m) instead. ^_^
 

Input
Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 ... S n.
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.
 



题意:求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;
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值