forked from chandan73933/Hacktoberfest2020-Algorithms-In-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsnack.cpp
More file actions
82 lines (72 loc) · 1.11 KB
/
knapsnack.cpp
File metadata and controls
82 lines (72 loc) · 1.11 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<bits/stdc++.h>
using namespace std;
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knap(int wt[],int pro[],int n,int w)
{
int k[n+1][w+1];
for(int j=0;j<=w;j++)
{
k[0][j]=0;
}
for(int i=0;i<=n;i++)
{
k[i][0]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=w;j++)
{
if(wt[i-1]>j)
{
k[i][j]=k[i-1][j];
}
else
{
k[i][j]= max(pro[i - 1] + k[i - 1][j - wt[i - 1]], k[i - 1][j]);
}
}
}
int inc[n];
int i=n;int s=w;
int j=0;
while(i>0 || s>0)
{
if(s>0 && k[i][s]!=k[i-1][s])
{
inc[j]=i;
j++;
i--;
s=s-wt[i];
}
else
{
i=i-1;
}
}
cout<<"The elements which are included in Knapsnack are : "<<endl;
for(int i=0;i<j;i++)
{
cout<<inc[i]<<" ";
}
cout<<"\n"<<"Total value of Knapsnack: ";
return k[n][w];
}
int main()
{
int n,w;
cout<<"enter the number of items in knapsnack:"<<endl;
cin>>n;
cout<<"enter the maximum weight of knapsnack:"<<endl;
cin>>w;
int wt[n],pro[n];
for(int i=0;i<n;i++)
{
cout<<"enter the weight and profit for item "<<i+1<<":"<<endl;
cin>>wt[i]>>pro[i];
}
cout<<knap(wt,pro,n,w)<<endl;
return 0;
}