HDU 1024 Max Sum Plus Plus (最大M子串和优化)

hdu 1024

题目:

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36636    Accepted Submission(s): 13050


 

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 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

题意:将一段数列找出m个不重合的组使得这m组数的和最大。

题解:这个题用动态规划解决, 简单来想可以用dp[i][j]表示前j 项找出i 组的最大值, 这样来定义递推关系。

 

有: dp[i][j] = max(dp[i][j - 1] + s[j] ,  max(dp[i - 1][k] + s[j])), 每遇到一个数字都有两种情况:

(1)将其加入到第i 组中不增加新组。

(2)将s[j]单独列成第i组, 寻找 前i - 1组中的最大值加起来。

取上述两种情况的最大值。

仔细看看不难发现max(dp[i - 1][k])就是上一组0 到 j - 1的最大值, 可以在每次循环时开一个maxx数组记录下下次要用的最大值。计算中只需要当前行以及上一行的数据, 因此这样数组可以优化到一维, 时间优化到O(n ^ 2)。

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int dp[1000005] = {0};//分组划分过程中计算只需要当前行和上一行, 因此数组只需要一维
int maxx[1000005] = {0};//用来存下上个分组中前j - 1项的最大值
int s[1000005];
int main()
{
    int i, j, n, ans, ma, m, k;
    while(~scanf("%d %d", &m, &k)){
        for(i = 1;i <= k;i++)
            scanf("%d", &s[i]);
        for(i = 1;i <= m;i++){//分成i组
            ans = -99999999;//赋ans最小值
            for(j = i;j <= k;j++){//枚举分组起点,分成i组至少要i个元素
                dp[j] = max(dp[j - 1] + s[j], maxx[j - 1] + s[j]);//两种情况的状态转移
                maxx[j - 1] = ans;//记录此次分组中前j - 1项的最大值
                ans = max(ans, dp[j]);//更新答案
            }
        }
        printf("%d\n", ans);
        memset(maxx, 0, sizeof(maxx));
        memset(dp, 0, sizeof(dp));
    }
    return 0;
}

点个赞吧~~谢谢。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值