Description
Try to design a function of searching a subset space tree by backtracking method. The parameters of the function include the necessary functions such as the node feasibility determination function and the upper bound function, and use this function to solve the 0-1 knapsack problem. 0-1 backpack The problem is described as follows: given n items and a backpack. The weight of item I is WI, its value is VI, the capacity of the backpack is C. 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? When selecting items for backpack, there are only 2 options for each item I put in the backpack or not in the backpack. Item I cannot be loaded into the backpack multiple times, nor can I only load part of the item I.
Input
The first line has 2 positive integers n and C. n is the number of items, and C is the capacity of the backpack. The next 1 rows have n positive integers representing the value of the item. There are n positive integers in line 3rd, indicating the weight of the item.
Output
Calculates the maximum value of loaded backpack items and the optimal loading scheme output. The first line is output as: Optimal value is
Sample Input
5 106 3 5 4 62 2 6 5 4
Sample Output
Optimal value is151 1 0 0 1
HINT
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int v[100],w[100],dp[100][100],c[100];
Int main () {
int n,m;
cin>>n>>m;
Memset (Dp,0,sizeof (DP));
for (int i=0;i<n;i++)
Cin>>v[i];
for (int i=0;i<n;i++)
Cin>>w[i];
for (int i=w[0];i<=m;i++)
Dp[0][i]=v[0];
for (int i=1;i<n;i++)
for (int j=m;j>=w[i];j--)
{
Dp[i][j]=max (dp[i-1][j],dp[i-1][j-w[i]]+v[i]);
}
//for (int i=0;i<n;i++) {
//for (int j=0;j<=m;j++) {
//cout<<dp[i][j]<< "";
}
//cout<<endl;}
cout<< "Optimal value is" <<endl;
cout<<dp[n-1][m]<<endl;
for (int i=n-1;i>=1;i--)
{
if (Dp[i][m]!=dp[i-1][m])
{c[i]=1; m-=w[i];}
Else c[i]=0;
}
if (m!=0) c[0]=1;
else c[0]=0;
cout<<c[0];
for (int i=1;i<n;i++)
cout<< "" <<c[i];
cout<<endl;
return 0;}
Ytu 2335:0-1 knapsack problem