-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.0_1KNAPSACK.CPP
More file actions
61 lines (52 loc) · 944 Bytes
/
7.0_1KNAPSACK.CPP
File metadata and controls
61 lines (52 loc) · 944 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
53
54
55
56
57
58
59
60
61
// 0/1 Knapsack problem//
#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
int main()
{
int a[100][100],w[100],p[100],m,n,i,j;
printf("How many element: ");
cin>>n;
printf("Bag size: ");
cin>>m;
printf("---------------------\n");
printf("Enter price & weight:\n");
printf("---------------------\n");
for(i=1;i<=n;i++)
{
printf("%d: ",i);
printf("Enter weight: ");
cin>>w[i];
printf("Enter price : ");
cin>>p[i];
}
for(j=0;j<=m;j++)
a[0][j]=0;
for(i=1;i<=n;i++)
for(j=0;j<=m;j++)
{
if(w[i]>j)
a[i][j]=a[i-1][j];
else
a[i][j]=max(a[i-1][j],p[i]+a[i-1][j-w[i]]);
}
cout<<"\n\n";
for(i=1;i<=n;i++)
{
for(j=0;j<=m;j++)
{
printf("%5d",a[i][j]) ;
}
cout<<"\n";
}
printf("\n Total profit: %d ",a[n][m]);
return 0;
}