Go语言解法
二维解法:
package main
import "fmt"
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
var N, V int
var v, w [1001]int
fmt.Scanln(&N, &V)
for i:=1; i<=N; i++ {
fmt.Scanln(&v[i], &w[i])
}
var dp [1001][1001]int
for i := 1; i <= N; i++ {
for j := 1; j <= V ; j++ {
if j >= v[i] {
dp[i][j] = max(dp[i-1][j], dp[i-1][j-v[i]]+w[i])
} else {
dp[i][j] = dp[i-1][j]
}
}
}
fmt.Println(dp[N][V])
}
一维解法:
package main
import "fmt"
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
var N, V int
var v, w [1001]int
fmt.Scanln(&N, &V)
for i:=1; i<=N; i++ {
fmt.Scanln(&v[i], &w[i])
}
var dp [1001]int
for i := 1; i <= N; i++ {
for j := V; j >= v[i]; j-- {
dp[j] = max(dp[j-v[i]]+w[i], dp[j])
}
}
fmt.Println(dp[V])
}