0-1 knapsack problem
0-1 knapsack Problem Descriptive narrative
There was a thief who stole a store and found that there were n items, and the item I was worth is vI, and the weight was WI. Ifboth V I and Wi are integers.
He hopes to take away the more valuable the better, but his backpack is more than just to fit the W-pound thing. W is an integer.
What kind of things should he take?
0-1 knapsack problem: Each item is either taken away or left behind (0-1 choices are required). Thieves cannot just take a part of an item or take more than two times the same item.
part of the knapsack problem: a thief can just take a part of an item. You don't have to make 0-1 choices .
0-1 knapsack Problem Solving method
0-1 knapsack problem is a typical problem with a common substructure, but it can only be solved by dynamic programming. Instead of using greedy algorithms. Because of the 0-1 knapsack problem. In choosing whether or not to add an item to the backpack, the solution to the sub-problem of the item must be added in order to compare the solution of the sub-problem that does not take the item. The problem caused by this way is a lot of overlapping sub-problems, which satisfies the characteristics of dynamic programming. Dynamic planning solves 0-1 knapsack problem processes such as the following:
0-1 knapsack problem substructure : Select a given item I, it is necessary to choose the optimal solution of the sub-problem of the formation of I and the sub-problem of not select I. Divided into two sub-problems, the selection of the comparison, choose the best.
0-1 knapsack problem recursive process: with n items, backpack weight of w,c[i][w] for the optimal solution. That
Code:
#include <iostream> #include <algorithm> #define MAX 1000using namespace Std;int dp[max][max];int Record[max ];int w;int knapsack (int n,int w[],int v[])//number of items N, value of goods v[i], weight of goods w[i]{int i,j;for (i=0;i<=n;i++)//Initialize boundary value dp[i][0]= 0;for (j=0;j<=w;j++) dp[0][j]=0;for (i=1;i<=n;i++) {for (j=1;j<=w;j++) {if (J<w[i]) dp[i][j]=dp[i-1][j]; Elsedp[i][j]=max (Dp[i-1][j],dp[i-1][j-w[i]]+v[i]);}} Construct the optimal solution J=w;for (i=n;i>0;i--) {if (Dp[i][j]>dp[i-1][j]) {record[i]=1;j-=w[i];} elserecord[i]=0;} return dp[n][w];} int main (int argc,char *argv[]) {int n;int i,j;int v[max],w[max];cout<< "Please input n=";cin>>n;cout< < "w=";cin>>w;cout<< "Please input value:" <<endl;for (i=1;i<=n;i++) cin>>v[ i];cout<< "Please input weight:" <<endl;for (j=1;j<=n;j++) cin>>w[j];cout<< "Max value is:" <<knapsack (n,w,v) <<endl;cout<< "Record: \ n"; for (i=1;i<=n;i++) cout<< "" <<record[i ];cout<<endl;return 0;}
0-1 knapsack problem