プログラミングコンテストチャレンジブック(2-3)
Dynamic Programmingで解く
package main import "fmt" const MAX_N int = 100 const MAX_W int = 10000 type knapsack struct { weight int value int } func max(i,j int) int{ if i > j { return i } return j } func main() { W := 5 N := 4 knap := []knapsack{{2,3},{1,2},{3,4},{2,2}} dp := [MAX_N][MAX_W]int{} for i := 0; i<N; i++ { for j :=0; j<=W; j++ { if j < knap[i].weight { dp[i+1][j] = dp[i][j] } else { dp[i+1][j] = max(dp[i][j], dp[i][j - knap[i].weight] + knap[i].value) } } } fmt.Println(dp[N][W]) }