竞争性编程简单

分数背包

“分数背包”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 fractional_knapsack(W, items) ,它接受背包容量 W 和元组列表 items ,其中每个元组是 (value, weight) 。找到背包中可获得的最大总价值,允许物品被打破/分割。将输出四舍五入到小数点后两位。

约束条件
  • 1 <= len(items) <= 1000
  • 1 <= W <= 10^5
  • 1 <= value, weight <= 10^4

示例

Example 1
Input
fractional_knapsack(50, [(60, 10), (100, 20), (120, 30)])
Output
240.0
Explanation

Take the first and second item fully, and 2/3 of the third item. Total value: 60 + 100 + 120 * (20/30) = 240.0.

Example 2
Input
fractional_knapsack(15, [(24, 10), (18, 10), (15, 10)])
Output
33.0
Explanation

Take the first item fully, and 1/2 of the second item. Total value: 24 + 18 * 0.5 = 33.0.

Need a Hint?
考虑使用特定于贪婪的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。