您的位置:首页 > 其它

hdu 1024 Max Sum Plus Plus

2015-09-09 13:06 288 查看
http://acm.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): 20887 Accepted Submission(s): 6960


[align=left]Problem Description[/align]
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. ^_^

[align=left]Input[/align]
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.

[align=left]Output[/align]
Output the maximal summation described above in one line.

[align=left]Sample Input[/align]

1 3 1 2 3

2 6 -1 4 -2 3 -2 3

[align=left]Sample Output[/align]

6
8

Hint

Huge input, scanf and dynamic programming is recommended.

题目大意:在一个元素个数为m的序列中取出互不交叉的n段,找出最大值

dp[i - 1][j - 1]表示前j - 1个数取i - 1段得到的最大和,第j个数a[j]有两种情况:

1.a[j]单独作为一段,为第i段;

2.a[j]是紧跟第j - 1个数a[j - 1]之后,仍是第i - 1段的一部分。

由于数据太大所以将二维数组转化为一维数组

Max[j]表示上一个状态最终得到的最大值

dp[j] = max(dp[j - 1] + a[j], Max[j - 1] + a[j]);

dp[j - 1] + a[j] 表示情况2 (a[j]是紧跟第j - 1个数a[j - 1]之后,仍是第i - 1段的一部分)

Max[j - 1] + a[j] 表示情况1 ( a[j]单独作为一段,为第i段)

详解亲请参考:

[b]http://blog.csdn.net/a342374071/article/details/6701544[/b]

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#define INF 0x3f3f3f3f
#define N 1000010

using namespace std;

int dp
, Max
, a
;

int main()
{
int n, m, sum;
while(~scanf("%d%d", &n, &m))
{
int i, j;
memset(dp, 0, sizeof(dp));
memset(Max, 0, sizeof(Max));
for(i = 1 ; i <= m ; i++)
scanf("%d", &a[i]);
for(i = 1 ; i <= n ; i++)//i表示选取的段数
{
sum = -INF;
for(j = i ; j <= m ; j++)//j表示元素的个数
{
dp[j] = max(dp[j - 1] + a[j], Max[j - 1] + a[j]);//此处见上面解释
Max[j - 1] = sum;//Max[j - 1]记录j - 1这一状态得到的最大值
sum = max(sum, dp[j]);
}
Max[j - 1] = sum;//状态更新
}
printf("%d\n", sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: