File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
algorithm/src/acwing/algorithmBasicCourse/5_dynamic_programming Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ package __dynamic_programming
2+
3+ /**
4+ @author: CodeWater
5+ @since: 2025/02/28
6+ @desc: 01背包问题
7+ **/
8+
9+ import (
10+ "fmt"
11+ )
12+
13+ const N = 1010
14+
15+ var (
16+ // n个物品 背包容量为m
17+ n , m int
18+ // v存每个物品的体积 w存每个物品的价值
19+ v , w [N ]int
20+ // f[i][j] = a: 在前i个物品中所选择的总体积小于等于j的最大价值a
21+ f [N ][N ]int
22+ )
23+
24+ func max (a , b int ) int {
25+ if a > b {
26+ return a
27+ }
28+ return b
29+ }
30+
31+ func main () {
32+ fmt .Scan (& n , & m )
33+ for i := 1 ; i <= n ; i ++ {
34+ fmt .Scan (& v [i ], & w [i ])
35+ }
36+
37+ // f[0][0-m],不选择物品时的价值是0,而f为包级变量默认数组值就是0,
38+ // 所以这里不用对这个进行初始化
39+
40+ // 直接从1开始
41+ for i := 1 ; i <= n ; i ++ {
42+ for j := 0 ; j <= m ; j ++ {
43+ f [i ][j ] = f [i - 1 ][j ]
44+ /*本题状态有两种:
45+ 1. f[i - 1][j]: 不选择当前物品,即上面一种恒存在状态,无需判断
46+ 2. f[i][j]: 选择当前物品,前提是当前背包容量得大于当前物品重量,不然下面的回退上一个状态计算当前状态会数组越界f[i-1][j-v[i]],所以有如下判断。正常应该是j - v[i] >= 0,这里为了方便做了个变形。
47+ */
48+ if j >= v [i ] {
49+ f [i ][j ] = max (f [i - 1 ][j ], f [i - 1 ][j - v [i ]]+ w [i ])
50+ }
51+ }
52+ }
53+
54+ fmt .Println (f [n ][m ])
55+ }
You can’t perform that action at this time.
0 commit comments