-
Notifications
You must be signed in to change notification settings - Fork 0
/
Knapsack_M3.c
72 lines (63 loc) · 958 Bytes
/
Knapsack_M3.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
62
63
64
65
66
67
68
69
70
71
72
#include<stdio.h>
void sort(int p[], int w[], int n)
{
int i,j,t;
float r[n],temp;
for(i=0;i<n;i++)
r[i]=(float)p[i]/w[i];
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(r[j]<r[j+1])
{
t=p[j];
p[j]=p[j+1];
p[j+1]=t;
t=w[j];
w[j]=w[j+1];
w[j+1]=t;
temp=r[j];
r[j]=r[j+1];
r[j+1]=temp;
}
}
}
}
int main()
{
int n,cap,i;
float s=0.0,t;
printf("Enter Number of Elements ");
scanf("%d",&n);
int p[n];
int w[n];
for(i=0;i<n;i++)
{
printf("Enter Profit & Weight of Item %d: ",i+1);
scanf("%d%d",&p[i],&w[i]);
}
printf("\n Enter the capacity ");
scanf("%d",&cap);
sort(p,w,n);// function call
for(i=0;i<n;i++)
{
if(cap==0)
break;
else if(w[i]<=cap)
{
printf("\n %d",p[i]);
s=s+p[i];
cap=cap-w[i];
}
else
{
t=p[i]*((float)cap/w[i]);
s=s+t;
printf("\n %.2f",t);
break;
}
}
printf("\n Total Profit %.2f",s);
return 0;
}