HDU 1024 Max Sum Plus Plus (递推)

Max Sum Plus Plus

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


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.

 

 

dp[i][j][0] ... 表示前i个数分成j个组,不选第i个数的最大得分

dp[i][j][1] ... 表示前i个数分成j个组,选第i个数的最大得分

因为状态i只跟状态i-1, 所以可以用滚动数组来减空间

取最要自己写 。 否则卡常数会超时

 

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std ;
const int N = 100010;
const int inf = 1e9+7;

int dp[2][N][2] , n , m , x[N] ;
inline int MAX( int a , int b ) {
    if( a > b ) return a ;
    else return b ;
}
int main() {
//    freopen("in.txt","r",stdin);
    while( ~scanf("%d%d",&m,&n) ) {
        for( int i = 1 ; i <= n ; ++i ) {
            scanf("%d",&x[i]);
        }
        int v = 0 ;
        dp[v][0][0] = 0 ;
        dp[v][1][1] = x[1] ;
        for( int i = 1 ; i < n ; ++i ) {
            for( int j = 0 ; j <= i + 1 && j <= m ; j++ ) {
                dp[v^1][j][0] = dp[v^1][j][1] = -inf ;
            }
            for( int j = min( m , i ) ; j >= 0 ; --j ) {
                if( j != i ) {
                    dp[v^1][j+1][1] = MAX( dp[v][j][0] + x[i+1] , dp[v^1][j+1][1] );
                    dp[v^1][j][0] = MAX( dp[v][j][0] , dp[v^1][j][0]);
                }
                if( j != 0 ) {
                    dp[v^1][j][1] =  MAX ( dp[v^1][j][1] , dp[v][j][1] + x[i+1] ) ;
                    dp[v^1][j+1][1] = MAX ( dp[v^1][j+1][1] , dp[v][j][1] + x[i+1] ) ;
                    dp[v^1][j][0] = MAX ( dp[v^1][j][0] , dp[v][j][1] ) ;
                }
            }
            v ^= 1 ;
        }
        int ans = -inf ;
        if( m < n ) ans = MAX( ans , dp[v][m][0] );
        if( m > 0 ) ans = MAX( ans , dp[v][m][1] );
        printf("%d\n",ans);
    }
    return 0 ;
}
View Code

 

posted @ 2015-03-28 11:28  hl_mark  阅读(170)  评论(0编辑  收藏  举报