-
Notifications
You must be signed in to change notification settings - Fork 0
/
knapsack.cpp
38 lines (36 loc) · 1.14 KB
/
knapsack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*----Knapsack problem algorithm----
Problem description:there are 'n' items,
where ith item weighs 'w[i]' and has value 'p[i]'
given the constraint of weighing capacity of
knapsack 'W' find the optimal solution which
maximizes value, there are unlimited copies of
each is available (not 0/1 knapsack problem)
author: Kishor Mohite
Organization: SDSLabs, IIT Roorkee
*/
#include<iostream>
using namespace std;
int K(int W,int w[],int p[],int n)
{
if(W==0) return 0; //base case, knapsack with zero capacity
else
{
int max=0;
for(int i=0;i<n;i++)
{
if(W-w[i]>=0&&K(W-w[i],w,p,n)+p[i]>max) max=K(W-w[i],w,p,n)+p[i];
/*if optimal solution requires ith item excluding it will give the solution for knapsack with
capacity W-w[i] go through all items to find which one to include*/
}
return max;
}
}
int main()
{
int w[100],p[100],n,W;
cin>>n;
cin>>W;
for(int i=0;i<n;i++) cin>>w[i]>>p[i];
cout<<K(W,w,p,n)<<endl;
system("pause");
}