-
Notifications
You must be signed in to change notification settings - Fork 0
/
Knapsack.cpp
56 lines (51 loc) · 1.05 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdlib.h>
#include<iostream>
using namespace std;
int max(int a,int b)
{
if(a>b)
return a;
return b;
}
void knapsack(int n,int wt[],int p[],int cap)
{
int v[10][10],i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=cap;j++)
{
if(i==0||j==0)
v[i][j]=0;
else if(j<wt[i])
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],v[i-1][j-wt[i]]+p[i]);
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=cap;j++)
{
cout<<v[i][j]<<" ";
}
cout<<"\n";
}
cout<<"The Optimized Value is :\t"<<v[n][cap];
}
int main()
{
int cap,n;
cout<<"Enter Capacity Of Knapsack ";
cin>>cap;
cout<<"Enter Total Count Of Elements :";
cin>>n;
int wt[n],v[n];
cout<<"Enter Capacity And Value OF Each Elements \n";
for(int i=0;i<n;i++)
{
cin>>wt[n]>>v[n];
}
cout<<"The Table is\n";
knapsack(n,wt,v,cap);
return 0;
}