You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
1.9 KiB
74 lines
1.9 KiB
8 months ago
|
/**
|
||
|
* File: unbounded_knapsack.kt
|
||
|
* Created Time: 2024-01-25
|
||
|
* Author: curtishd (1023632660@qq.com)
|
||
|
*/
|
||
|
|
||
|
package chapter_dynamic_programming
|
||
|
|
||
|
import kotlin.math.max
|
||
|
|
||
|
/* 完全背包:動態規劃 */
|
||
|
fun unboundedKnapsackDP(
|
||
|
wgt: IntArray,
|
||
|
value: IntArray,
|
||
|
cap: Int
|
||
|
): Int {
|
||
|
val n = wgt.size
|
||
|
// 初始化 dp 表
|
||
|
val dp = Array(n + 1) { IntArray(cap + 1) }
|
||
|
// 狀態轉移
|
||
|
for (i in 1..n) {
|
||
|
for (c in 1..cap) {
|
||
|
if (wgt[i - 1] > c) {
|
||
|
// 若超過背包容量,則不選物品 i
|
||
|
dp[i][c] = dp[i - 1][c]
|
||
|
} else {
|
||
|
// 不選和選物品 i 這兩種方案的較大值
|
||
|
dp[i][c] = max(dp[i - 1][c].toDouble(), (dp[i][c - wgt[i - 1]] + value[i - 1]).toDouble())
|
||
|
.toInt()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return dp[n][cap]
|
||
|
}
|
||
|
|
||
|
/* 完全背包:空間最佳化後的動態規劃 */
|
||
|
fun unboundedKnapsackDPComp(
|
||
|
wgt: IntArray,
|
||
|
value: IntArray,
|
||
|
cap: Int
|
||
|
): Int {
|
||
|
val n = wgt.size
|
||
|
// 初始化 dp 表
|
||
|
val dp = IntArray(cap + 1)
|
||
|
// 狀態轉移
|
||
|
for (i in 1..n) {
|
||
|
for (c in 1..cap) {
|
||
|
if (wgt[i - 1] > c) {
|
||
|
// 若超過背包容量,則不選物品 i
|
||
|
dp[c] = dp[c]
|
||
|
} else {
|
||
|
// 不選和選物品 i 這兩種方案的較大值
|
||
|
dp[c] =
|
||
|
max(dp[c].toDouble(), (dp[c - wgt[i - 1]] + value[i - 1]).toDouble()).toInt()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return dp[cap]
|
||
|
}
|
||
|
|
||
|
/* Driver Code */
|
||
|
fun main() {
|
||
|
val wgt = intArrayOf(1, 2, 3)
|
||
|
val value = intArrayOf(5, 11, 15)
|
||
|
val cap = 4
|
||
|
|
||
|
// 動態規劃
|
||
|
var res = unboundedKnapsackDP(wgt, value, cap)
|
||
|
println("不超過背包容量的最大物品價值為 $res")
|
||
|
|
||
|
// 空間最佳化後的動態規劃
|
||
|
res = unboundedKnapsackDPComp(wgt, value, cap)
|
||
|
println("不超過背包容量的最大物品價值為 $res")
|
||
|
}
|