AcWing 1024. 装箱问题python3
原题链接
简单
# 原题可以看成:背包问题,只不过价值变成了每个物品的体积
# 原题可以改为:在总体积不变的情况下,背包里物品的体积最大是多少
from typing import List
class Solution:
def box(self, stuff: List[int], space: int):
dp = [[0 for _ in range(space+1)] for _ in range(len(stuff)+1)]
for i in range(1, len(dp)):
for j in range(1, len(dp[0])):
if j >= stuff[i-1]:
dp[i][j] = max(dp[i-1][j], dp[i-1][j-stuff[i-1]]+stuff[i-1])
else:
dp[i][j] = dp[i-1][j]
return dp[-1][-1]
if __name__ == '__main__':
solution = Solution()
space = int(input())
nums = int(input())
stuff = []
for i in range(nums):
stuff.append(int(input()))
res = solution.box(stuff, space)
print(space-res)