HDU1024——Max Sum Plus Plus(dp)



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


Sample Output
6 8
題意:
給定一個數組,求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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章