#include <stdio.h>
#include <stdlib.h>
struct Fruit {
char name[10];
int weights;
int price;
};
int compare(const void *a, const void *b)
{
int ratioA = ((struct Fruit*)a)->price / ((struct Fruit*)a)->weights;
int ratioB = ((struct Fruit*)b)->price / ((struct Fruit*)b)->weights;
return ratioB - ratioA;
}
int greedyKnapsack(struct Fruit fruits[], int n, int capacity) {
qsort(fruits, n, sizeof(struct Fruit), compare);
int totalprice = 0;
int currentweights = 0;
for (int i = 0; i < n; ++i) {
int remainingweights = capacity - currentweights;
if (remainingweights > 0 && fruits[i].weights <= remainingweights) {
currentweights += fruits[i].weights;
totalprice += fruits[i].price;
printf("%s(%dkg),", fruits[i].name, fruits[i].weights);
} else if (remainingweights > 0) {
int fraction = (remainingweights * fruits[i].price) / fruits[i].weights;
totalprice += fraction;
printf("%s(%dkg部分),", fruits[i].name, remainingweights);
break;
}
}
return totalprice;
}
int main() {
struct Fruit fruits[] = {
{"苹果", 15, 300},
{"香蕉", 18, 180},
{"橘子", 10, 150},
{"猕猴桃", 9, 270}
};
int n = sizeof(fruits) / sizeof(fruits[0]);
int capacity = 20;
int maxTotalprice = greedyKnapsack(fruits, n, capacity);
printf("\n背包中水果的总价值为:%d 元\n", maxTotalprice);
return 0;
}