</pre><pre class= "cpp" name= "code" ><span style= "FONT-SIZE:14PX;" > #include <iostream> #include <vector> #include <iterator> #include <algorithm> #include <string>using namespace std;/**0-1 knapsack problem (Recursive implementation) *///int * * Values;//values[i][j] Indicates the maximum number of items in a backpack with a capacity of j in the first I item ( Two-dimensional array scheme one) vector<vector<int>> Values;//values[i][j] represents the maximum value of items in a backpack with a capacity of j in the first I item (two-dimensional array scheme II) int knapsack ( vector<int>& w,vector<int>& v,int I,int vol) {if (i==0| | vol==0) return Values[i][vol] = 0;if (Vol<w[i]) {return Values[i][vol] = knapsack (W,v,i-1,vol);} if (Vol>=w[i]) {int fi = knapsack (w,v,i-1,vol); int se = knapsack (w,v,i-1,vol-w[i]) +v[i];return Values[i][vol] = max (fi , SE);}} void Printres (vector<int>& w,int I,int vol) {if (i<=0) return, if (Values[i][vol]>values[i-1][vol]) { Printres (W,i-1,vol-w[i]); cout<<i<< "";} Else{printres (W,i-1,vol);}} int main () {vector<int> w;//Item weight vector<int> v;//Item Value int vol;w.push_back (0);//v.puSh_back (0);//copy (istream_iterator<int> (CIN),istream_iterator<int> (), Back_inserter (w)); Cin.clear () ; Cin.sync (); Copy (Istream_iterator<int> (CIN),istream_iterator<int> (), Back_inserter (v)); Cin.clear (); Cin.sync (); cin>>vol;//Create and initialize the V array/*values = new int*[w.size ()]; (two-dimensional array scheme one) for (int i = 0; i < w.size (); i++) {values[i] = new int[vol+1];} *///(two-dimensional array scheme er) values = vector<vector<int>> (W.size (),vector<int> (vol+1));//functions that run the Find solution knapsack ( W,v,w.size () -1,vol);//output 0-1 backpack results </span><span style= "FONT-SIZE:14PX;" >printres (W,w.size () -1,vol); </span><span style= "FONT-SIZE:14PX;" >}</span>
Input Example:
The first line enters the weight of each item
Enter the value of each item in the second line
The third line is the maximum bearing weight of the backpack.
0-1 knapsack problem (Recursive implementation)