HDU1024——Max Sum Plus Plus(dp)

来源:互联网 发布:淘宝客怎么关闭 编辑:程序博客网 时间:2024/06/05 07:41


Max Sum Plus Plus

点击获取最新情报

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


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 32 6 -1 4 -2 3 -2 3
 


Sample Output
68
题意:
给定一个数组,求m个不相交子段最大值。
解题思路:
dp[i][j] = max( dp[i][j-1] + a[j], dp[i-1][j-1] + a[j] ).
dp[i][j]表示数组到第j个数时分成i段最大的值(好好理解),dp[i][j-1]+a[j]表示第j个数包括在第i段的情况,dp[i-1][j-1]+a[j]表示第j个数是第i段的第一个数的情况。
由于题目的要求是1,000,000个数而且每个数又很大,所以用二维数组很快就爆栈了,这里咱们采用两个一维滚动数组,核心思想是一样的。
now[j] 数组表示第j个数包括在第i段 , pre[j]数组表示第j个数是第i段的开头。

核心代码

for(i=1;i<=m;i++)

 {             Max=-99999999;     for(j=i;j<=n;j++) // 想想j为什么从=i开始     {           now[j]=max(now[j-1]+a[j],pre[j-1]+a[j]);           //now[j]有两种来源,一种是直接在第i个子段之后添加a[j]           //一种是是a[j]单独成为1个子段           pre[j-1]=Max;       //更新pre使得pre是前j-1个中最大子段和           if(now[j]>Max)  Max=now[j];     }

 }

出处

代码实现:

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;typedef long long LL;const int maxn = 1000000+10;const int inf = -0x7fffffff;int a[maxn];int pre[maxn];int now[maxn];int MAX;int main(){    int m, n;    while( ~scanf("%d%d",&m,&n) )    {        memset(a,0,sizeof(a));        memset(pre,0,sizeof(pre));        memset(now,0,sizeof(now));        int i,j;        for( i=1; i<=n; i++ )            scanf("%d",&a[i]);        for( i=1; i<=m; i++ )        {            MAX = inf;            for( j=i; j<=n; j++ )            {                                              // 顺序不能颠倒,想想颠倒的后果;                now[j] = max(now[j-1]+a[j], pre[j-1]+a[j]);                pre[j-1] = MAX;                MAX = max(MAX, now[j]);            }        }        printf("%d\n",MAX);    }        return 0;}

0 0