揹包DP

gebeng發表於2024-04-05

01揹包

image

定義dp[i][j]表示從前i件物品中選,體積不超過 j 的最大價值

N, V = map(int, input().split())
v = [0] * (N + 1)
w = [0] * (N + 1)
for i in range(1,N + 1):
    v[i],w[i] = map(int,input().split())
f = [[0] * (V + 1) for _ in range(N + 1)]
# 對於第i件物品,選或不選!
for i in range(1, N + 1):
    for j in range(V, -1, -1):
        if j < v[i]:
            f[i][j] = f[i - 1][j]
        else:
            f[i][j] = max(f[i - 1][j], f[i - 1][j - v[i]] + w[i])
print(f[N][V])

相關文章