hdu 1024 Max Sum Plus Plus

本文解析了 HDU 1024 题目的求解思路,采用动态规划的方法找到给定数组中 m 个互不相交子序列的最大和,并附带 AC 代码。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1024

 

题目描述:

 

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

 

 

 

 

题目大意:

给出m和n,在长为n的一维数组s中,找出m个互不相交的字串,使得和最大

 

题目分析:

跟最大和子序列思想相同,只不过这里不再是一个子序列,而是有m个,我们可以很自然地想到用二维dp来解决这个问题,dp[i][j]代表前j个数分成i组,dp[i][j]=max(dp[i][j-1]+v[j],max(dp[i-1][1~j-1]+v[j]);。可是用二维的话会超时,这里就需要我们用背包的思想来简化,另开一组maxx数组来记录前面一段(即i-1段)的最大值。

 

AC代码:

 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int v[1000005],dp[1000005],maxx[1000005],maxnum;
int n,m;

int main()
{
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
            cin>>v[i];
        memset(dp,0,sizeof(dp));
        memset(maxx,0,sizeof(maxx));
        for(int i=1;i<=m;i++)
        {
            maxnum=-0xfffffff;
            for(int j=i;j<=n;j++)
            {
                //dp[i][j]代表前j个数分成i组
                //dp[i][j]=max(dp[i][j-1]+v[j],max(dp[i-1][1~j-1]+v[j]);
                dp[j]=max(dp[j-1]+v[j],maxx[j-1]+v[j]);
                maxx[j-1]=maxnum;
                maxnum=max(maxnum,dp[j]);
            }
        }
        cout<<maxnum<<endl;
    }
    return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值