Max Sum Plus Plus HDU 1024

Solution:
let dp[i][j] be the max sum of the previous j consecutive numbers divided into i groups,
of course end with a[j], then we consider whether put the j-th number into i-th group
if we do , that is dp[i][j-1] + a[j]
else we do not, then a[j] must be alone in one group ,which is the i-th group
so how about the previous i-1 groups and j-1 number ? we don’t really know how they
are grouped and what is the ending element of each group , but for dp[i][j] the previous
state can be dp[i-1][k],(0<k<j) for we don’t know the ending element of group i
so we can only enumerate the ending element for group i-1
the result of enumeration id max{dp[i-1][k]|0<k<j} ,by observation ,we can figure out this is
exactly the state dp[i][j] we calculated in the last outer for-cycle
let it be pre[j-1] we take the max index of k as its index
then the final state is pre[j-1] + a[j]

here it is

 for(int i=1; i<=m; i++)
{
    for(int j=i; j<=n; j++) //j start from i because each group has at least one element
    {
        dp[i][j]=max(dp[i][j-1] + a[j],last_dp[i][j](pre[j-1]) + a[j]
        //update pre[j-1]
    }
}
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn = 1e6+7;
int a[maxn],dp[maxn],pre[maxn];
int n,m,temp;
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        for(int i=1; i<=n; i++)
        {
            scanf("%d",a+i);
            dp[i]=pre[i]=0;
        }
        for(int i=1; i<=m; i++)
        {
            temp=-INF;
            for(int j=i; j<=n; j++)
            {
                dp[j]=max(dp[j-1]+a[j], pre[j-1] +a[j]);
                /**
                pre[j-1] is always updated after temp so is last max{dp[i-1][k]|0<k<j}
                */
                pre[j-1]=temp;
                temp=max(dp[j],temp);
            }
        }
        ///we should let max{dp[i]|1<=i<=n} be the answer ,but temp is already the max
        printf("%d\n",temp);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值