HDU 1024 Max Sum Plus Plus(最大m子段和)

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. ^_^ 
InputEach 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. 
OutputOutput 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.

        题目大意:给一个长度为n的数组,从中挑出m组连续的数,要求这m组数不交叉重叠,问这m组数的最大和为多少。

        思路:动态规划,根据0~j的分成的段数把大问题分解成一个个子问题,dp[i][j]表示 从0~j数,组成i段数的和的最大值  则得到            以下状态转移方程

            dp[i][j]=Max(dp[i][j-1]+a[j] , max( dp[i-1][k] ) + a[j] ) 0<k<j

            其中: 若新加的数a[j]与前面的数串连续,则加上后  仍然是i段 即 dp[i][j]=dp[i][j-1]+a[j];

                      若a[j]与前面不连续,则这时0~j中 多了一组数。在这里:(max( dp[i-1][k] ) + a[j] )  

                      就表示 0~k中,分成i-1段的最大值,再加上不连续的数a[j]则表示0~j中分成i段的最大值  即:dp[i][j]

             这样其动态转移方程就写出来了,但是对这个题,给的数太大了,暴内存啊。。。。因此要进行状态压缩

              仔细观察你会发现dp[j],dp[j-1]有关,(max(dp[i-1][k])+a[j])并不需要单独求,可以在求本次状态方程时,对该状态               进行同步更新(不懂的话  等下在代码里有解释)

下面上代码:


#include<stdio.h>
#include<iostream>
#include<algorithm>
#define maxn 1000010
#define inf 0x7fffffff
int a[maxn];
int dp[maxn],mmax[maxn];
using namespace std;
int main()
{
    int m,n,i,j;
    int maxx;
    while(~scanf("%d%d",&m,&n)){
        for(i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        memset(mmax,0,sizeof(mmax));
        memset(dp,0,sizeof(dp));
        for(i=0;i<m;i++){  //表示分成i段
            maxx=-inf;
            for(j=i;j<n;j++){//注意这里  由于分成i段,则j不可能小于i,从i开始遍历
                dp[j]=max(dp[j-1]+a[j],mmax[j-1]+a[j]);  //在mmax[j-1]是从上一个状态求得的 即i-1时
                mmax[j-1]=maxx;   //为下一个状态做好准备  注意这里为了不影响对当下状态的求解,并且能为下一状态做好数据准备  需要mmax[j-1]=maxx
                maxx=max(maxx,dp[j]); //储存该状态最大值,注意这句话的顺序不能与上一句对调

            }
        }
        printf("%d\n",maxx);
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值