dp - bailian 4131:Charm Bracelet

Topic Link

http://bailian.openjudge.cn/practice/4131/

Analysis of problem-solving

This is the basis of a 01 knapsack problem using dynamic programming to solve, because the title to the M, which is the maximum capacity is relatively large backpack, a two-dimensional array may exceed memory, so you can use the scroll array of ways to save space.
State transition equation: dp [i] [j] = max {dp [i-1] [j], dp [i-1] [jw [i]] + p [i]}
initial state: dp [0] [ J] = 0;
DP [i] [J] is defined: i-th previous selected items, so that the total weight of no more than j, the maximum desirable obtained.
State total dp transition equation [i-1] [J], denotes the front i-selected items, the weight of no more than j, dp [i-1] [jw [i]], represents a front selected i-1 th article, JW capacity not exceeding [i], denotes the i th previous items are not selected, the latter represents the i-th item selection.
If the solution with an array of rolling method, remove dp [i] [j] in the i dimension, which is placed in circulation, only the change dp [i] [j] in a row. Because dp [i-1] [j ], dp [i-1] [jw [i]] respectively dp [i] [j] of the upper left and upper elements, if you want to dp [i] [j] of writing position value dp [i-1] [j ] , we need to dp [i-1] [j ] is not in use, it is necessary to traverse forward from the maximum of j.

Problem-solving Code

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int dp[14000];
int w[4000];
int p[4000];
int N, M;

int main(){
    scanf("%d%d", &N, &M);
    for(int i = 1; i <= N; i++){
        scanf("%d%d", &w[i], &p[i]);
    }
    
    memset(dp, 0, sizeof(dp));
    
    for(int i = 1; i <= N; i++){
        for(int j = M; j >= w[i]; j--){
            dp[j] = max(dp[j], dp[j - w[i]] + p[i]);
        }
    }
    
    printf("%d\n", dp[M]);
}

Guess you like

Origin www.cnblogs.com/zhangyue123/p/12588715.html