-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack Problem.c
More file actions
70 lines (57 loc) · 1.92 KB
/
Knapsack Problem.c
File metadata and controls
70 lines (57 loc) · 1.92 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
67
68
69
70
#include <stdio.h>
struct Item {
int profit, weight;
float ratio;
};
void sortItems(struct Item items[], int n) {
struct Item temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (items[j].ratio < items[j + 1].ratio) {
temp = items[j];
items[j] = items[j + 1];
items[j + 1] = temp;
}
}
}
}
void fractionalKnapsack(struct Item items[], int n, int capacity) {
float totalProfit = 0.0;
int i;
for (i = 0; i < n; i++) {
if (items[i].weight <= capacity) {
totalProfit += items[i].profit;
capacity -= items[i].weight;
} else {
totalProfit += items[i].profit * ((float)capacity / items[i].weight);
break;
}
}
printf("The solution of the problem will be: %.3f\n", totalProfit);
}
int main() {
int n, capacity;
printf("Enter the number of elements: ");
scanf("%d", &n);
struct Item items[n];
for (int i = 0; i < n; i++) {
printf("Enter the profit and weight of %d%s element: ", i + 1, (i + 1 == 1) ? "st" : (i + 1 == 2) ? "nd" : (i + 1 == 3) ? "rd" : "th");
scanf("%d %d", &items[i].profit, &items[i].weight);
items[i].ratio = (float)items[i].profit / items[i].weight;
}
printf("\nItems details:\n");
printf("Item\tProfit\tWeight\tProfit/Weight Ratio\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\t%d\t%.2f\n", i + 1, items[i].profit, items[i].weight, items[i].ratio);
}
printf("\nProfit/Weight ratios of the items are: ");
for (int i = 0; i < n; i++) {
printf("%.2f ", items[i].ratio);
}
printf("\n");
printf("Enter the capacity of the knapsack: ");
scanf("%d", &capacity);
sortItems(items, n);
fractionalKnapsack(items, n, capacity);
return 0;
}