HDU 1024 Max Sum Plus Plus(经典DP)
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
Hint
Huge input, scanf and dynamic programming is recommended.
题面大意 :
给出 m, n两个数, 以及 n 个数, 将这 n 个数分成 m 组, 当然也可以不选, 求这 m 组的和的最大值。
题解 :
相信大家都是一眼看出这是一道 dp, 其实这是一道比较经典的 dp 题, 当然在 HDU 中还有许多的变形, 比如 HDU 1224 有兴趣的话可以去做一下。
我们定义 dp[i][j] 表示将前 j 个数分成 i 组的最大的和, 我们可以得到转移方程 : dp[i][j]=max(dp[i][j−1]+a[j],max(dp[i−1][k]+a[j]))(0<k≤j−1) 分别表示独立成组, 或和前面的状态成组, 于是我们就愉快的得到了一个复杂度为 : O(m∗n∗n) 的 dp, 但是这道题 n ≤ 100000, 考虑优化。
我们可以看到 dp[i][j] 只与 dp[i][j - 1] 以及 dp[i - 1] 的所有状态有关, 其实这是一个比较常见的套路, 当 dp 只与上个状态有关, 我们都可以记录前面的最优解然后优化掉一个 n, 比如这里我们就记录 dp[i - 1] 中最大的值, 这样我们就不用去遍历 k了。
这时我们发现, 我们的空间炸了,因为 m 一旦大了, 就 1e7或者更高的定义, 考虑优化,因为我们dp[i - 1] 的所有的信息我们都已经存下来了,于是dp[i - 1] 这个状态我们用不到了, 于是我们舍去就可以降成一维 dp 了, 于是这道题就愉快的想出来了。
代码 :
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <ctime>
#include <map>
#include <vector>
using namespace std;
inline int read() {
int i = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') f = -1; ch = getchar();
}
while(ch >= '0' && ch <= '9') {
i = (i << 3) + (i << 1) + ch - '0'; ch = getchar();
}
return i * f;
}
const int MAXN = 1e6 + 10;
int dp[MAXN], mx[MAXN], a[MAXN];
int main() {
int n, m;
while(scanf("%d%d", &m, &n) != EOF) {
for(int i = 1; i <= n; ++i) a[i] = read(), dp[i] = 0, mx[i] = 0;
int x = 0;
for(int i = 1; i <= m; ++i) {
x = -0x3f3f3f3f;
for(int j = i; j <= n; ++j) {
dp[j] = max(dp[j - 1] + a[j], mx[j - 1] + a[j]);
mx[j - 1] = x;
x = max(x, dp[j]);
}
}
printf("%d\n", x);
}
}
本题结束 :
感谢阅读本篇文章,喜欢的话,点个赞吧,你的鼓励就是我最大的动力
有什么意见,尽情发表吧。