HDU-1024 Max Sum Plus Plus(M段连续子段和+dp图表规律优化)

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(极光炫影)

 

#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
#define MAXN 1000005
#define INF 0x3f3f3f3f
//养成暴力枚举的思维
//额,很容易联想到最大连续子序列,这种序列的动态规划,强调到某个元素为止时的最大,也就是说利用这个最后的元素做讨论
//那我们可以定义dp[i][j]表示前i个数取j段,a[i]必须取时的最大值
//这样我们可以推出递推公式
//f[i][j] = max(f[i-1][j]+a[i], f[k][j-1]+a[i])   (k>=j-1&&k<=i) ( j-1 可以有多种情况的)
//考虑到不可能开到10^6*10^6这样大的数组,所以要优化
//画表找规律优化
//反正10^8是可以开的
typedef __int64 LL;
int a[MAXN],dp[MAXN]; //dp表示长度为j时的最大值
int pre[MAXN];
int main()
{
    int n,m;
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        memset(dp,0,sizeof(a));
        memset(pre,0,sizeof(pre));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        int maxn;
        for(int i=1;i<=m;i++)
        {
            maxn=-INF;      //maxn每次在i的循环中都会重置,所以maxn最终存的就是i==m时的最大值
            for(int j=i;j<=n;j++)
            {
                dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]); //dp[j-1]对第一个数而言就是 上一行的左边第一个
                pre[j-1]=maxn;                         //对于非第一个数而言,就是左边第一个数
                maxn=max(dp[j],maxn);                  //pre[j-1]存的就是同行左边的最大值
            }                                          //pre每用一次就更新一次
        }
        printf("%d\n",maxn);
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值