HDU1024-Max Sum Plus Plus(dp)

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1024

题意:

给定一个序列A,长度为n,从中找出m段,使其和最大,其中n <= 1000000,m > 0

思路:

d[i][j]表示在将第i个数选入第j段的最大和,则目标max(d[k][m]),其中k ∈ [m, n];
对A[i],可以和A[i - 1]放入同一段,也可以开辟新的一段,于是转移方程为:

d[i][j] = max(d]i -1][j], d[k][j - 1]) + a[i]; (j - 1 <= k <= i - 1);

状态数:nm, 转移:n,时间复杂度O(m*n^2),明显会T,并且也会MLE
对d[k][j - 1]为前i - 1项的最大和,于是可以单独用一个数组pre[]保存,每次循环的时候更新,以及循环的时候注意循环顺序
并且对d[i][j]和d[i][j - 1],第二项j可以直接省去,于是:

d[i] = max(d[i - 1], pre[i - 1]) + a[i];

代码:

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl

const int maxn = 1000000 + 5;
int a[maxn], n, m;
LL d[maxn], pre[maxn];

void dp() {
    memset(d, 0, sizeof(d));
    memset(pre, 0, sizeof(pre));
    LL res;
    for (int j = 1; j <= m; j++) {
        res = -0x3e3e3e3e;
        for (int i = j; i <= n; i++) {
            d[i] = max(d[i - 1], pre[i - 1]) + a[i];
            pre[i - 1] = res;
            res = max(res, d[i]);
        }
    }
    printf("%lld\n", res);
}

int main() {
    while (~scan(m)) {
        scan(n);
        for (int i = 1; i <= n; i++) scan(a[i]);
        dp();
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值