1. 程式人生 > >HDU 1024 Max Sum Plus Plus(最大m子段和)

HDU 1024 Max Sum Plus Plus(最大m子段和)

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 S  1, S  2, S  3, S  4 ... S  x, ... S  n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S  x ≤ 32767). We define a function sum(i, j) = S  i + ... + S  j (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(i  1
, j  1) + sum(i  2, j  2) + sum(i  3, j  3) + ... + sum(i  m, j  m) maximal (i  x ≤ i  y ≤ j  x or i  x ≤ j  y ≤ j  x 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(i  x
, j  x)(1 ≤ x ≤ m) instead. ^_^ 
InputEach test case will begin with two integers m and n, followed by n integers S  1, S  2, S  3 ... S  n
Process to the end of file. 
OutputOutput 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.

        題目大意:給一個長度為n的陣列,從中挑出m組連續的數,要求這m組數不交叉重疊,問這m組數的最大和為多少。

        思路:動態規劃,根據0~j的分成的段數把大問題分解成一個個子問題,dp[i][j]表示 從0~j數,組成i段數的和的最大值  則得到            以下狀態轉移方程

            dp[i][j]=Max(dp[i][j-1]+a[j] , max( dp[i-1][k] ) + a[j] ) 0<k<j

            其中: 若新加的數a[j]與前面的數串連續,則加上後  仍然是i段 即 dp[i][j]=dp[i][j-1]+a[j];

                      若a[j]與前面不連續,則這時0~j中 多了一組數。在這裡:(max( dp[i-1][k] ) + a[j] )  

                      就表示 0~k中,分成i-1段的最大值,再加上不連續的數a[j]則表示0~j中分成i段的最大值  即:dp[i][j]

             這樣其動態轉移方程就寫出來了,但是對這個題,給的數太大了,暴記憶體啊。。。。因此要進行狀態壓縮

              仔細觀察你會發現dp[j],dp[j-1]有關,(max(dp[i-1][k])+a[j])並不需要單獨求,可以在求本次狀態方程時,對該狀態               進行同步更新(不懂的話  等下在程式碼裡有解釋)

下面上程式碼:


#include<stdio.h>
#include<iostream>
#include<algorithm>
#define maxn 1000010
#define inf 0x7fffffff
int a[maxn];
int dp[maxn],mmax[maxn];
using namespace std;
int main()
{
    int m,n,i,j;
    int maxx;
    while(~scanf("%d%d",&m,&n)){
        for(i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        memset(mmax,0,sizeof(mmax));
        memset(dp,0,sizeof(dp));
        for(i=0;i<m;i++){  //表示分成i段
            maxx=-inf;
            for(j=i;j<n;j++){//注意這裡  由於分成i段,則j不可能小於i,從i開始遍歷
                dp[j]=max(dp[j-1]+a[j],mmax[j-1]+a[j]);  //在mmax[j-1]是從上一個狀態求得的 即i-1時
                mmax[j-1]=maxx;   //為下一個狀態做好準備  注意這裡為了不影響對當下狀態的求解,並且能為下一狀態做好資料準備  需要mmax[j-1]=maxx
                maxx=max(maxx,dp[j]); //儲存該狀態最大值,注意這句話的順序不能與上一句對調

            }
        }
        printf("%d\n",maxx);
    }
    
    return 0;
}