-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathg5(knapsack).cpp
More file actions
52 lines (52 loc) · 842 Bytes
/
g5(knapsack).cpp
File metadata and controls
52 lines (52 loc) · 842 Bytes
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
/*fifth program*/
#include<iostream.h>
#include<conio.h>
int w[10],p[10],n,m;
void knapsack();
int max(int,int);
void main()
{
int i;
clrscr();
cout<<"enter the no. of elements\n";
cin>>n;
cout<<"enter the weights of all elements\n";
for(i=1;i<=n;i++)
cin>>w[i];
cout<<"enter profit of all elements\n";
for(i=1;i<=n;i++)
cin>>p[i];
cout<<"enter knapsack capacity\n";
cin>>m;
knapsack();
}
int max(int x,int y)
{
if(x>y)return x;
else return y;
}
void knapsack()
{
int i,j,v[10][10];
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
if(i==0||j==0)
v[i][j]=0;
else if(j-w[i]<0)
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
}
}
cout<<"output is\n";
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
cout<<v[i][j]<<"\t";
cout<<endl<<endl;
}
cout<<"optimal solutuion is:"<<v[n][m];
getch();
}