Given n kinds of goods and a backpack. The weight of item I is WI, its value is VI, the capacity of the backpack is C. Q. How do you choose which items are loaded into your backpack so that the total value of the items loaded into your backpack is greatest ?
The entire solution of the space equivalent of a binary tree, the left is 0, the representative does not take this item, the right is 1, the representative take this item, and then DFS, backtracking when modified.
Note that there should be two pruning here, and I only wrote one here.
#include <iostream> #include <string> #include <cstring>using namespace Std;int n,totcap,bestval;// Number of items, backpack capacity, maximum value const int N=1000;int val[n],w[n],x[n],bestx[n];//Item value, weight of item, X[i] selection of temporary items, item selection void Dfs (int i, int Cv,int cw) {//CW Current in-package item weight, CV current in-Package item value if (I>N)//End {if (cv>bestval) {BESTVAL=CV; for (i=1;i<=n;i++) bestx[i]=x[i]; }} else for (int j=0;j<=1;j++) {x[i]=j;//takes or does not take if (CW+X[I]*W[I]<=TOTCA p) {Cw+=w[i]*x[i]; Cv+=val[i]*x[i]; DFS (I+1,CV,CW); Cw-=w[i]*x[i]; Cv-=val[i]*x[i]; }}}int Main () {int i; bestval=0; cout<< "Please enter the maximum capacity of the backpack:" <<endl;; cin>>totcap; cout<< "Please enter the number of items:" <<endl; cin>>n; cout<< "Please enter the weight of the item in turn:" <<endl; for (i=1;i<=n;i++) cin>>w[i]; cout<< "Please enter the value of the item in turn:" <<endL for (i=1;i<=n;i++) cin>>val[i]; DFS (1,0,0); cout<< "Maximum value:" <<endl; cout<<bestval<<endl; cout<< "The label of the selected item is:" <<endl; for (i=1;i<=n;i++) if (bestx[i]==1) cout<<i<< ""; cout<<endl; return 0;}
Retrospective solution of 0-1 knapsack problem (Wang Xiaodong of the law problem)