HDU - 1024 Max Sum Plus Plus (basic dp)

Original title link:

Meaning of the questions:

Give you a length \ (N \) sequences. You want to be divided into \ (M \) segments do not overlap the continuum, so that the sum of these intervals the maximum.

Ideas:

We start with the state of view. General questions about the sequence it is easy to think of the first \ (j \) state at the end of the number. This question is then combined \ (M \) different intervals, then we can set up a number of interval \ (I \) state. And last \ (dp [i] [j ] \) represented by section \ (J \) end of the number, is divided into \ (\ I) state of intervals.

Let us analyze the state transition: we know \ (dp [i] [j ] \) may be made of \ (dp [i] [j -1] + arr [j] \) come, that is, we take the first \ (J \ ) bits and preceding it with a computer linked to the same interval (i.e., no change in the case where the number of sections)

Another is the number of intervals \ (1 + \) case. We can from the \ (dp [i-1] [k] + arr [j] \) to give. Here \ (K \) than \ (i-1 \) larger than \ (J \) small all states. (Because of \ (i-1 \) intervals so that the end of at least \ (i-1 \) , and because from \ (J \) so only to a state before the \ (. 1-J \) )

We look at the number of questions in sequence, in \ (10 ^ 6 \) is too large, and we have also been previously \ (dp [i] [j ] \ space = \ space max (dp [i] [j- 1] + arr [j], dp [i-1] [k] + arr [j]) \) this state transition equation, found by only two states \ (i, i-1 \ ) recursive. so, we use the scroll array. Although the name is actually Advanced Because each recursive related only to two adjacent states, so do not need to record information before. Then on \ (dp [i-1] [k] + arr [j] \) most value, we can a range of MAX to record the type used in the state of recursion.

code:


#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
const int inf = 0x3f3f3f3f;
int dp[2][maxn];
int arr[maxn];

int main(){
    int n,m;
    while(~scanf("%d %d",&n,&m)){
        for(int i=1;i<=m;i++){
            dp[0][i] = dp[1][i] = 0;
            scanf("%d",&arr[i]);
        }
        dp[1][0] = dp[0][0] = 0;
        int r = 1;//r表示当前状态 
        int Max;
        for(int i=1;i<=n;i++){
            Max = -inf;
            for(int j=i;j<=m;j++){
                dp[r][j] = max(dp[r][j-1],dp[r^1][j-1])+arr[j];
                dp[r^1][j-1] = Max;
                Max = max(Max,dp[r][j]);
            }           
        }
        printf("%d\n",Max);
    }
}

Guess you like

Origin www.cnblogs.com/Tianwell/p/11407932.html