AcWing 2. 01背包问题-二维数组-golang
原题链接
简单
作者:
一只鱼
,
2021-03-19 00:16:54
,
所有人可见
,
阅读 267
01背包问题-二维数组-golang
golang
package main
import "fmt"
var n, v int
var vi, wi []int
var value [][]int
func main(){
fmt.Scanf("%d%d", &n, &v)
vi, wi = make([]int, n+1), make([]int, n+1)
value = make([][]int, n+1)
for i := 0; i <= n; i++{
value[i] = make([]int, v+1)
}
for i := 1; i <=n; i++{
fmt.Scanf("%d%d", &vi[i], &wi[i])
}
for i := 1; i <= n; i++{
for j := 1; j <= v; j++{
//体积不够
if vi[i] > j{
value[i][j] = value[i-1][j]
}else{
value[i][j] = max(value[i-1][j], value[i-1][j-vi[i]]+wi[i])
}
}
}
fmt.Println(value[n][v])
}
func max(a, b int)int{
if a > b{
return a
}
return b
}