def fractional_knapsack(items, capacity): items = sorted(items, key=lambda item: item[1]/item[0], reverse=True) total_value = 0 for item in items: if capacity >= item[0]: capacity -= item[0] total_value += item[1] else: total_value += item[1] * (capacity / item[0]) capacity = 0 break return total_value items = [(2, 3), (3, 4), (4, 5)] # 每个元素为(重量, 价值) capacity = 5 print(fractional_knapsack(items, capacity))