mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-26 18:17:13 +00:00
build
This commit is contained in:
@@ -276,9 +276,36 @@ status: new
|
||||
=== "Dart"
|
||||
|
||||
```dart title="fractional_knapsack.dart"
|
||||
[class]{Item}-[func]{}
|
||||
/* 物品 */
|
||||
class Item {
|
||||
int w; // 物品重量
|
||||
int v; // 物品价值
|
||||
|
||||
[class]{}-[func]{fractionalKnapsack}
|
||||
Item(this.w, this.v);
|
||||
}
|
||||
|
||||
/* 分数背包:贪心 */
|
||||
double fractionalKnapsack(List<int> wgt, List<int> val, int cap) {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
List<Item> items = List.generate(wgt.length, (i) => Item(wgt[i], val[i]));
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
items.sort((a, b) => (b.v / b.w).compareTo(a.v / a.w));
|
||||
// 循环贪心选择
|
||||
double res = 0;
|
||||
for (Item item in items) {
|
||||
if (item.w <= cap) {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += item.v / item.w * cap;
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
Reference in New Issue
Block a user