-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnapsack.c
61 lines (52 loc) · 1.13 KB
/
Knapsack.c
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
#include<stdio.h>
int main()
{
int KS,n;
printf("Enter Capacity : ");
scanf("%d",&KS);
printf("Enter item: ");
scanf("%d",&n);
int unitprice[n];
for(int i=0; i<n; i++)
{
printf(" Item #%d unit price :",i+1);
scanf("%d",&unitprice[i]);
}
int weight[n];
for(int i=0; i<n; i++)
{
printf(" Item #%d weight :",i+1);
scanf("%d",&weight[i]);
}
int NN[n];
for(int i=0; i<n; i++)
{
NN[i]=0;
}
int maxprofit = 0;
while(KS != 0)
{
int max = 0, ind;
for(int i=0; i < 4 ; i++)
{
if(unitprice[i] > max && NN[i] == 0)
{
max = unitprice[i];
ind = i;
}
}
NN[ind] = 1;
if(weight[ind] < KS)
{
maxprofit += (unitprice[ind] * weight[ind]);
KS -= weight[ind];
}
else
{
maxprofit += (unitprice[ind] * KS);
KS = 0;
}
}
printf("The max profit = %d\n", maxprofit);
return 0;
}