AcWing 2. 01背包问题
原题链接
简单
作者:
Minions
,
2019-02-02 11:30:59
,
所有人可见
,
阅读 2831
Go 代码
package main
import (
"fmt"
)
func main() {
var N,V int
fmt.Scanf("%d %d\n", &N, &V)
var dp [][]int
for i := 0; i < N+1; i++ {
arr := make([]int, V+1)
dp = append(dp, arr)
}
v := make([]int, N)
w := make([]int, N)
for i := 0; i < N; i++ {
fmt.Scanf("%d %d\n", &v[i], &w[i])
}
for i := 1; i <= N; i++ {
for j := 1; j <= V; j++ {
if j >= v[i-1] {
dp[i][j] = max(dp[i-1][j], dp[i-1][j-v[i-1]]+w[i-1])
} else {
dp[i][j] = dp[i-1][j]
}
}
}
fmt.Println(dp[N][V])
}
func max(a,b int) int {
if a > b {
return a
}
return b
}