def greedy_knapsack(fruits, capacity):
fruits.sort(key=lambda x: x[2] / x[1], reverse=True)
total_value = 0
packed_fruits = []
for name, weight, value in fruits:
if weight <= capacity:
packed_weight = weight
packed_fruits.append((name, packed_weight))
capacity -= packed_weight
total_value += value
else:
fraction = capacity / weight
packed_weight = weight * fraction
packed_fruits.append((name, packed_weight))
total_value += value * fraction
capacity = 0
if capacity == 0:
break
return packed_fruits, total_value
fruits = [
('苹果', 15, 300),
('香蕉', 18, 180),
('橘子', 10, 150),
('猕猴桃', 9, 270)
]
capacity = 20
packed_fruits, total_value = greedy_knapsack(fruits, capacity)
print(f'装入背包的水果和它们的重量: {packed_fruits}')
print(f'背包中水果的总价值: {total_value}')