-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack.c
More file actions
66 lines (60 loc) · 1.67 KB
/
knapsack.c
File metadata and controls
66 lines (60 loc) · 1.67 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
#include <stdio.h>
void swap (float *a, float *b) {
float temp = *a;
*a = *b;
*b = temp;
}
void sortlist (float p[], float w[], float pw[], int n) {
for (int i = 0; i < n - 1; i ++) {
for (int j = 0; j < n - 1 - i; j ++) {
if (pw[j] < pw[j + 1]) {
swap(&pw[j], &pw[j + 1]);
swap(&p[j], &p[j + 1]);
swap(&w[j], &w[j + 1]);
}
}
}
}
int main () {
int n;
printf("Enter number of items in list : ");
scanf("%d", &n);
float p[n], w[n], pw[n];
printf("Enter details of items : \n");
for (int i = 0; i < n; i ++) {
printf("Profit of item %d = ", i + 1);
scanf("%f", &p[i]);
printf("Weight of item %d = ", i + 1);
scanf("%f", &w[i]);
pw[i] = p[i] / w[i];
}
int m;
printf("Enter max weight of knapsack = ");
scanf("%d", &m);
sortlist(p, w, pw, n);
printf("\nSorted lists : ");
printf("\nP[n] ");
for (int i = 0; i < n; i ++) printf("%.2f ", p[i]);
printf("\nW[n] ");
for (int i = 0; i < n; i ++) printf("%.2f ", w[i]);
printf("\nP/W ");
for (int i = 0; i < n; i ++) printf("%.2f ", pw[i]);
float x[n] , profit = 0;
for (int i = 0; i < n; i ++) x[i] = 0;
for (int i = 0; i < n; i ++) {
if (w[i] <= m) {
m -= w[i];
profit += p[i];
x[i] = 1;
} else {
float temp = m/w[i];
x[i] = temp;
profit += (p[i] * temp);
break;
}
}
printf("\n\nX ");
for (int i = 0; i < n; i ++) printf("%.2f ", x[i]);
printf("\nFinal profit = %.2f", profit);
return 0;
}