hdu 1024 Max Sum Plus Plus

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


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段,找出最大值

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

 

详解亲请参考:

http://blog.csdn.net/a342374071/article/details/6701544

 

#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[N], Max[N], a[N];

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

 

posted @ 2015-09-09 13:06  午夜阳光~  阅读(115)  评论(0编辑  收藏  举报