Title Link: http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1085
Test instructions: Chinese question eh ~
Idea: 01 knapsack template problem.
Using Dp[i][j] to represent the maximum value that the I-item spends on J space can store, then obviously there is
1 for(intI=1; i<=n; i++){2 for(intj=0; j<=m; J + +{//Note that J here is starting from 0 instead of A[i]3 if(j>=A[i]) {4Dp[i][j]=max (dp[i-1][j-a[i]]+b[i], dp[i-1][j]);5}Else{6dp[i][j]=dp[i-1][j];7 }8 }9}
AC Code:
1#include <bits/stdc++.h>2 #defineMAXN 1103 #defineMans 100104 using namespacestd;5 6 intDp[maxn][man];//Dp[i][j] Represents the maximum value that a J-space can store to the first I item7 8 intMainvoid){9 intN, M, A[MAXN], B[MAXN];//N is the number of items, M is the backpack capacity, A, b respectively stores the volume and value of the itemTenscanf"%d%d", &n, &m); One for(intI=1; i<=n; i++){ Ascanf"%d%d", &a[i], &b[i]); - } -Memset (DP,0,sizeof(DP)); the for(intI=1; i<=n; i++){ - for(intj=0; j<=m; J + +){ - if(j>=A[i]) { -Dp[i][j]=max (dp[i-1][j-a[i]]+b[i], dp[i-1][j]); +}Else{ -dp[i][j]=dp[i-1][j]; + } A } at } -printf"%d\n", Dp[n][m]); - return 0; -}
We can also open only one-dimensional array, using DP[J] to show the value of the largest can be installed after the J space
So the code we can write:
1#include <bits/stdc++.h>2 #defineMAXN 100103 using namespacestd;4 5 intDP[MAXN];//Dp[j] Represents the maximum value that a flower can store in J Space6 7 intMainvoid){8 intN, M, A[MAXN], B[MAXN];//N is the number of items, M is the backpack capacity, A, b respectively stores the volume and value of the item9scanf"%d%d", &n, &m);Ten for(intI=1; i<=n; i++){ Onescanf"%d%d", &a[i], &b[i]); A } -Memset (DP,0,sizeof(DP)); - for(intI=1; i<=n; i++){ the for(intJ=m; j>=a[i]; j--) {//This is pushed from the back forward -Dp[j]=max (dp[j-a[i]]+B[i], dp[j]); - } - } +printf"%d\n", Dp[m]); - return 0; +}
51nod1085 (01 Backpack)