-
Notifications
You must be signed in to change notification settings - Fork 0
/
Knapsack.c
69 lines (58 loc) · 1.47 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
62
63
64
65
66
67
68
69
#include<stdio.h>
void main()
{
int n,last=0;
float max,tp=0,tw=0,rw=0;
printf("Enter Capacity : ");
scanf("%f",&max);
printf("Enter Number of objects : ");
scanf("%d",&n);
float w[n],p[n];
float pw[n];
time_t t1,t2;
for(int i=0;i<n;i++)
{
printf("Enter Weight of Object %d : ",i+1);
scanf("%f",&w[i]);
printf("Enter Profit of Object %d : ",i+1);
scanf("%f",&p[i]);
}
time(&t1);
for(int i=0;i<n;i++)
{
pw[i]=p[i]/w[i]; //profit/weight ratio...
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1;j++)
{
if(pw[j]<pw[j+1])
{
float temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
float temp1=p[j]; // Sorting in descending order according to p/w ratio
p[j]=p[j+1];
p[j+1]=temp1;
float temp2=pw[j];
pw[j]=pw[j+1];
pw[j+1]=temp2;
}
}
}
for(int i=0;i<n;i++)
{
if(w[i]<=max)
{
max= max-w[i];
tp=tp+p[i];
last=i;
} //Calculation of maximum profit...
}
tp=tp+(max/w[last+1])*p[last+1];
time(&t2);
// max=max-w[k];
t2=t2-t1;
printf("Maximum Profit : %f",tp);
printf("\nTime : %ld",t2*1000);
}