HDU1024 Max Sum Plus Plus —— DP + 滚动数组

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

Max Sum Plus Plus

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

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.

 
Author
JGShining(极光炫影)
 
 
 
题解:
1.设last_max[i][j]为:处理到第j个数时,第j个数属于第i个序列的最大值。last_max[i][j]必定包含a[j]。
2.设all_max[i][j]为 :处理到第j个数时, 分成i个序列的最大值。all_max[i][j]不一定包含a[j], 其值实际上是 max( last_max[i][k] )   其中i<=k<=j,all_max数组的实际作用是:当a[j]独立出来自己作为一个序列时,找到前面i-1个序列和的最大值, 以便与a[j]拼接成i个序列。
3.状态转移:last_max[i][j] = max( last_max[i][j-1],  all_max[i-1][j-1] ) + a[j]。即以a[j]是否独立出来自己作为一个序列来讨论。
4.观察状态转移方程, last_max数组不需要知道上一步的信息,所以只需要开一维;all_max数组只需要知道上一步的信息,所以可以用滚动数组以节省空间。
 
 
代码如下:
 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
#define ms(a,b) memset((a),(b),sizeof((a)))
using namespace std;
typedef long long LL;
const double EPS = 1e-;
const int INF = 2e9;
const LL LNF = 2e18;
const int MAXN = 1e6+; int a[MAXN];
int last_max[MAXN], all_max[][MAXN];
int main()
{
int n, m;
while(scanf("%d%d",&m, &n)!=EOF)
{
for(int i = ; i<=n; i++)
scanf("%d", &a[i]); ms(all_max, );
ms(last_max, ); for(int i = ; i<=m; i++)
{
last_max[i] = all_max[i&][i] = last_max[i-]+a[i];
for(int j = i+; j<=n; j++)
{
last_max[j] = max(last_max[j-], all_max[!(i&)][j-]) + a[j];
all_max[i&][j] = max(all_max[i&][j-], last_max[j]);
/**以上代码的实际意义为:
last_max[i][j] = max(last_max[i][j-1], all_max[i-1][j-1]) + a[j];
all_max[i][j] = max(all_max[i][j-1], last_max[i][j]);
**/
}
}
printf("%d\n", all_max[m&][n]);
}
return ;
}
上一篇:HDU 1024 Max Sum Plus Plus【DP】


下一篇:安装Python图型处理库Python Imaging Library(PIL)