AcWing 3. 完全背包问题
原题链接
简单
作者:
u
,
2019-04-04 20:20:00
,
所有人可见
,
阅读 1452
golang
// script.go
package main
import (
"fmt"
"os"
)
func main() {
var N, V int
fmt.Fscanln(os.Stdin, &N, &V)
vw := make([][]int, N)
for i := range vw {
var v, w int
fmt.Fscanln(os.Stdin, &v, &w)
vw[i] = []int{v, w}
}
fmt.Println(backpack(vw, N, V))
}
func backpack(vw [][]int, N int, V int) int {
dp := make([][]int, N+1)
for i := range dp {
dp[i] = make([]int, V+1)
}
for i := 1; i <= N; i++ {
for j := 1; j <= V; j++ {
item := int(j/vw[i-1][0]) + 1
for k := 0; k < item; k++ {
if j-k*vw[i-1][0] >= 0 {
dp[i][j] = max(max(dp[i-1][j], dp[i-1][j-k*vw[i-1][0]]+k*vw[i-1][1]), dp[i][j])
}
}
}
}
return dp[N][V]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
# a.txt
4 5
1 2
2 4
3 4
4 5
# how to run
go run script.go < a.txt