#include <stdio.h>
#include <stdlib.h>
struct Bean {
int weight;
int value;
double unitValue;
};
int compareUnitValue(const void *a, const void *b) {
return ((struct Bean *)b)->unitValue - ((struct Bean *)a)->unitValue;
}
double greedyBeanKnapsack(struct Bean *beans, int n, int capacity) {
for (int i = 0; i < n; ++i) {
beans[i].unitValue = (double)beans[i].value / beans[i].weight;
}
qsort(beans, n, sizeof(struct Bean), compareUnitValue);
double totalValue = 0.0;
int currentWeight = 0;
for (int i = 0; i < n && currentWeight < capacity; ++i) {
int selectedWeight = (beans[i].weight < capacity - currentWeight) ? beans[i].weight : capacity - currentWeight;
totalValue += selectedWeight * beans[i].unitValue;
currentWeight += selectedWeight;
}
return totalValue;
}
int main() {
struct Bean beans[] = {{10, 60}, {20, 100}, {30, 120}};
int n = sizeof(beans) / sizeof(beans[0]);
int capacity = 50;
double maxValue = greedyBeanKnapsack(beans, n, capacity);
printf("Maximum value that can be obtained = %.2lf\n", maxValue);
return 0;
}