# Dynamic planning-0-1 knapsack problem

Source: Internet
Author: User

The 0-1 knapsack problem is described as follows:

There is a backpack with a capacity of V, and some items. These items have two properties, Volume W and value V, and only one for each item. Ask for the maximum value of the item that is worth as much as possible with this back, and the backpack may not be filled. Because there are two possible cases for each item in the optimal solution, either in the backpack or absent (there are 0 items or 1 in the backpack), we call this problem the 0-1 knapsack problem.

Use dp[i][j] to indicate that the top I items in the overall product does not exceed J, the maximum value placed in the backpack. Thus, the state transfer equation can be introduced:

DP[0][J] = 0;

DP[I][J] = Max{dp[i-1][j-v[i]] + w[i],dp[i-1][j]};

The above formula should be well understood, when the volume of item I is less than the current remaining volume, it can be loaded into the backpack, then dp[i][j] = Dp[i-1][j-v[i]]+w[i]. On the other hand, can not be transferred to the backpack, dp[i][j] = dp[i-1][j].

`#include <iostream>using namespacestd;#defineMAXSIZE 100intW[maxsize];intV[maxsize];intMAXV;intN;intDp[maxsize][maxsize];intMaxintAintb) {    if(A >b)returnA; Else        returnb;}intMain () {CIN>> N >>MAXV;  for(inti =1; I <= N; i++) {cin>> W[i] >>V[i]; }     for(inti =0; I <= MAXV; i++) dp[0][i] =0;  for(inti =1; I <= N; i++)    {        //only when J >= W[i],dp[i][j] can select the maximum value         for(intj = MAXV; J >= W[i]; j--) {Dp[i][j]= Max (Dp[i-1][J], Dp[i-1][j-w[i]] +V[i]); }                //when J < W[i], stating that the item I is not able to transfer to the backpack, so dp[i][j] = Dp[i-1][j]         for(intj = W[i]-1; J >=0; j--) Dp[i][j]= Dp[i-1][j]; } cout<< DP[N][MAXV] <<Endl; return 0;}`

Dynamic planning-0-1 knapsack problem

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.