This commit is contained in:
krahets
2024-05-15 19:00:27 +08:00
parent bd54cd096b
commit e434a3343c
36 changed files with 402 additions and 107 deletions
@@ -496,9 +496,39 @@ comments: true
=== "Ruby"
```ruby title="fractional_knapsack.rb"
[class]{Item}-[func]{}
### 物品 ###
class Item
attr_accessor :w # 物品重量
attr_accessor :v # 物品价值
[class]{}-[func]{fractional_knapsack}
def initialize(w, v)
@w = w
@v = v
end
end
### 分数背包:贪心 ###
def fractional_knapsack(wgt, val, cap)
# 创建物品列表,包含两个属性:重量,价值
items = wgt.each_with_index.map { |w, i| Item.new(w, val[i]) }
# 按照单位价值 item.v / item.w 从高到低进行排序
items.sort! { |a, b| (b.v.to_f / b.w) <=> (a.v.to_f / a.w) }
# 循环贪心选择
res = 0
for item in items
if item.w <= cap
# 若剩余容量充足,则将当前物品整个装进背包
res += item.v
cap -= item.w
else
# 若剩余容量不足,则将当前物品的一部分装进背包
res += (item.v.to_f / item.w) * cap
# 已无剩余容量,因此跳出循环
break
end
end
res
end
```
=== "Zig"
+18 -1
View File
@@ -310,7 +310,24 @@ comments: true
=== "Ruby"
```ruby title="coin_change_greedy.rb"
[class]{}-[func]{coin_change_greedy}
### 零钱兑换:贪心 ###
def coin_change_greedy(coins, amt)
# 假设 coins 列表有序
i = coins.length - 1
count = 0
# 循环进行贪心选择,直到无剩余金额
while amt > 0
# 找到小于且最接近剩余金额的硬币
while i > 0 && coins[i] > amt
i -= 1
end
# 选择 coins[i]
amt -= coins[i]
count += 1
end
# 若未找到可行方案, 则返回 -1
amt == 0 ? count : -1
end
```
=== "Zig"
+22 -1
View File
@@ -397,7 +397,28 @@ $$
=== "Ruby"
```ruby title="max_capacity.rb"
[class]{}-[func]{max_capacity}
### 最大容量:贪心 ###
def max_capacity(ht)
# 初始化 i, j,使其分列数组两端
i, j = 0, ht.length - 1
# 初始最大容量为 0
res = 0
# 循环贪心选择,直至两板相遇
while i < j
# 更新最大容量
cap = [ht[i], ht[j]].min * (j - i)
res = [res, cap].max
# 向内移动短板
if ht[i] < ht[j]
i += 1
else
j -= 1
end
end
res
end
```
=== "Zig"
@@ -371,7 +371,19 @@ $$
=== "Ruby"
```ruby title="max_product_cutting.rb"
[class]{}-[func]{max_product_cutting}
### 最大切分乘积:贪心 ###
def max_product_cutting(n)
# 当 n <= 3 时,必须切分出一个 1
return 1 * (n - 1) if n <= 3
# 贪心地切分出 3 ,a 为 3 的个数,b 为余数
a, b = n / 3, n % 3
# 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
return (3.pow(a - 1) * 2 * 2).to_i if b == 1
# 当余数为 2 时,不做处理
return (3.pow(a) * 2).to_i if b == 2
# 当余数为 0 时,不做处理
3.pow(a).to_i
end
```
=== "Zig"