-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfractional_knapsack.c
58 lines (51 loc) · 1.6 KB
/
fractional_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
#include <stdio.h>
#include <stdlib.h>
struct Item {
int value;
int weight;
};
int compare(const void *a, const void *b) {
double ratioA = ((struct Item *)a)->value / (double)((struct Item *)a)->weight;
double ratioB = ((struct Item *)b)->value / (double)((struct Item *)b)->weight;
if (ratioA < ratioB) {
return 1;
} else if (ratioA > ratioB) {
return -1;
} else {
return 0;
}
}
double fractionalKnapsack(struct Item items[], int n, int capacity) {
int i;
qsort(items, n, sizeof(struct Item), compare);
int currentWeight = 0;
double totalValue = 0.0;
for (i = 0; i < n; i++) {
if (currentWeight + items[i].weight <= capacity) {
currentWeight += items[i].weight;
totalValue += items[i].value;
} else {
int remainingWeight = capacity - currentWeight;
totalValue += items[i].value * ((double)remainingWeight / items[i].weight);
break;
}
}
return totalValue;
}
int main() {
int n,i;
printf("Enter the number of items: ");
scanf("%d", &n);
struct Item items[n];
for (i = 0; i < n; i++) {
printf("Enter the profit and weight of item %d: ", i + 1);
scanf("%d %d", &items[i].value, &items[i].weight);
}
int capacity;
printf("Enter the capacity of the knapsack: ");
scanf("%d", &capacity);
double maxValue = fractionalKnapsack(items, n, capacity);
printf("The maximum value that can be obtained is: %.2lf\n", maxValue);
return 0;
}
//complexity : O(NlogN)