This commit is contained in:
krahets
2024-04-09 20:43:40 +08:00
parent d8caf02e9e
commit a6adc8e20a
48 changed files with 1599 additions and 571 deletions

View File

@ -462,29 +462,25 @@ comments: true
/* 物品 */
class Item(
val w: Int, // 物品
val v: Int // 物品价值
val v: Int // 物品价值
)
/* 分数背包:贪心 */
fun fractionalKnapsack(
wgt: IntArray,
value: IntArray,
c: Int
): Double {
fun fractionalKnapsack(wgt: IntArray, _val: IntArray, c: Int): Double {
// 创建物品列表,包含两个属性:重量、价值
var cap = c
val items = arrayOfNulls<Item>(wgt.size)
for (i in wgt.indices) {
items[i] = Item(wgt[i], value[i])
items[i] = Item(wgt[i], _val[i])
}
// 按照单位价值 item.v / item.w 从高到低进行排序
Arrays.sort(items, Comparator.comparingDouble { item: Item -> -(item.v.toDouble() / item.w) })
items.sortBy { item: Item? -> -(item!!.v.toDouble() / item.w) }
// 循环贪心选择
var res = 0.0
for (item in items) {
if (item!!.w <= cap) {
// 若剩余容量充足,则将当前物品整个装进背包
res += item.v.toDouble()
res += item.v
cap -= item.w
} else {
// 若剩余容量不足,则将当前物品的一部分装进背包
@ -497,25 +493,21 @@ comments: true
}
/* 分数背包:贪心 */
fun fractionalKnapsack(
wgt: IntArray,
value: IntArray,
c: Int
): Double {
fun fractionalKnapsack(wgt: IntArray, _val: IntArray, c: Int): Double {
// 创建物品列表,包含两个属性:重量、价值
var cap = c
val items = arrayOfNulls<Item>(wgt.size)
for (i in wgt.indices) {
items[i] = Item(wgt[i], value[i])
items[i] = Item(wgt[i], _val[i])
}
// 按照单位价值 item.v / item.w 从高到低进行排序
Arrays.sort(items, Comparator.comparingDouble { item: Item -> -(item.v.toDouble() / item.w) })
items.sortBy { item: Item? -> -(item!!.v.toDouble() / item.w) }
// 循环贪心选择
var res = 0.0
for (item in items) {
if (item!!.w <= cap) {
// 若剩余容量充足,则将当前物品整个装进背包
res += item.v.toDouble()
res += item.v
cap -= item.w
} else {
// 若剩余容量不足,则将当前物品的一部分装进背包

View File

@ -381,8 +381,8 @@ $$
// 循环贪心选择,直至两板相遇
while (i < j) {
// 更新最大容量
val cap = (min(ht[i].toDouble(), ht[j].toDouble()) * (j - i)).toInt()
res = max(res.toDouble(), cap.toDouble()).toInt()
val cap = min(ht[i], ht[j]) * (j - i)
res = max(res, cap)
// 向内移动短板
if (ht[i] < ht[j]) {
i++

View File

@ -357,14 +357,14 @@ $$
val b = n % 3
if (b == 1) {
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
return 3.0.pow((a - 1).toDouble()).toInt() * 2 * 2
return 3.0.pow((a - 1)).toInt() * 2 * 2
}
if (b == 2) {
// 当余数为 2 时,不做处理
return 3.0.pow(a.toDouble()).toInt() * 2 * 2
return 3.0.pow(a).toInt() * 2 * 2
}
// 当余数为 0 时,不做处理
return 3.0.pow(a.toDouble()).toInt()
return 3.0.pow(a).toInt()
}
```