目录
一、2. 01背包问题 - AcWing题库
使用滚动数组优化空间
# N = 1010
# v, w = [0] * N, [0] * N
# f = [[0] * N for _ in range(N)]
# R = lambda: map(int, input().split())
# n, m = R()
# for i in range(1, n + 1):
# v[i], w[i] = R()
# for j in range(m + 1):
# f[i][j] = f[i - 1][j]
# if j >= v[i]:
# f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i])
# print(f[n][m])
# 一维优化
N= 1010
f = [0] * N
R = lambda: map(int, input().split())
n, m = R()
for i in range(1, n + 1):
v, w = R()
for j in range(m, v - 1, -1):
# 逆序更新,保证f[j - v]是未被更新的(i-1)层
f[j] = max(f[j], f[j - v] + w)
print(f[m])
二、3. 完全背包问题 - AcWing题库
N = 1010
f = [0] * N
R = lambda: map(int, input().split())
n, m = R()
for i in range(1, n + 1):
v, w = R()
for j in range(v, m + 1):
# f[i][j] = max(f[i - 1][j], f[i][j - v] + w)
f[j] = max(f[j], f[j - v] + w)
print(f[m])
完
感谢你看到这里!一起加油吧!