0-1 Knapsack In C++
#include<iostream>
using namespace std;
int weight[]={10, 20, 30};
int price []={60, 100, 120};
int capasity=50;
int i,n=sizeof(weight)/sizeof(weight[0]);
int func(int i,int w)
{
int profit1=0;
int profit2=0;
if(i==n+1)
return 0;
if(w+weight[i]<=capasity)
profit1=price[i]+func(i+1,w+weight[i]);
else
profit1=0;
profit2=func(i+1,w);
return max(profit1,profit2);
}
int main()
{
cout<<func(1,0)<<endl;
}
No comments