HDU - 1024 DP

Max Sum Plus Plus

Topic meaning:

  • Give you n numbers, let you find m consecutive and disjoint intervals from them, and then make the sum of all interval elements to be the largest.

data range:

1 n 10 6 , 32768 a i 32767 m > 0

Problem solving ideas:

First determine a state, dp[i][j] represents the maximum value of group i formed by the first j numbers, and the state transition equation is:

d p [ i ] [ j ] = m a x ( d p [ i ] [ j 1 ] , m a x ( d p [ i 1 ] [ k ] ) ) + a [ j ] ( 1 k < j )
The first part is to add the jth to the i-1th segment, and the latter part is that the ith segment starts with the jth element. But what makes this question a bit uncomfortable is that his m doesn't tell you the specific range, but this question can only be used O ( n m ) The complexity of the state transition equation dp[i][j] can be transferred from dp[i][j-1], it is only related to the previous state, so it can be replaced by a one-dimensional array, that is,
d p [ j ] = m a x ( d p [ j 1 ] , M a x [ j ] ) + a [ j ] ( That middle M a x [ j ] generation surface d p [ k ] ( 1 k < j ) of most Big value )
Then use Maxm to record the maximum value when it is divided into m segments, which is the final answer.

AC code:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
const LL INF = 1LL << 50;
const int maxn = 1e6;
LL Max[maxn + 5];
LL dp[maxn + 5];
LL a[maxn + 5];
LL Maxm;
int n, m;
int main() {
    while(scanf("%d%d", &m, &n) != EOF) {
        for(int i = 1; i <= n; i++)scanf("%lld", &a[i]);
        memset(dp, 0, sizeof(dp));
        memset(Max, 0, sizeof(Max));
        for(int i = 1; i <= m; i++) {
            Maxm = -INF;//Maxm每次初始化为-oo
            for(int j = i; j <= n; j++) {
                dp[j] = max(dp[j - 1], Max[j]) + a[j];
                Max[j] = Maxm;//Max[j]记录上一状态前j-1个的最大值。
                Maxm = max(Maxm, dp[j]);
            }
        }
        printf("%lld\n", Maxm);
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324502165&siteId=291194637