-
Notifications
You must be signed in to change notification settings - Fork 0
/
knapsack01.cpp
40 lines (36 loc) · 986 Bytes
/
knapsack01.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
39
40
/*----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 (0/1 knapsack)
author: Kishor Mohite
Organization: SDSLabs, IIT Roorkee
*/
#include<iostream>
using namespace std;
int ma(int a,int b)
{if(a>b) return a; else return b;}
int K(int W,int w[],int p[],int n)
{
if(W==0||n==0) return 0; //base case, knapsack with zero capacity
else
{
int max=0;
for(int i=0;i<n;i++)
{
if(w[i]>W) max=K(W,w,p,i);
else max=ma(K(W-w[i],w,p,i)+p[i],K(W,w,p,i));
}
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");
}