#include <stdio.h>
#include <stdbool.h>
struct Item {
char name[20];
int value;
int weight;
};
float calculateUnitValue(struct Item item) {
return (float)item.value / item.weight;
}
void sortByUnitValue(struct Item items[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (calculateUnitValue(items[j]) < calculateUnitValue(items[j + 1])) {
struct Item temp = items[j];
items[j] = items[j + 1];
items[j + 1] = temp;
}
}
}
}
void knapsack(struct Item items[], int n, int capacity) {
sortByUnitValue(items, n);
int currentWeight = 0;
float totalValue = 0.0;
for (int i = 0; i < n; i++) {
if (currentWeight + items[i].weight <= capacity) {
currentWeight += items[i].weight;
totalValue += items[i].value;
printf("偷取 %s,价值: %d 美元,重量: %d\n", items[i].name, items[i].value, items[i].weight);
}
}
printf("总价值:%0.2f 美元\n", totalValue);
}
int main() {
struct Item items[] = {
{"音响", 3000, 4},
{"笔记本电脑", 2000, 3},
{"吉他", 1500, 1}
};
int n = sizeof(items) / sizeof(items[0]);
int capacity = 4;
printf("背包容量:%d\n", capacity);
knapsack(items, n, capacity);
return 0;
}