From fda18c06b7221b1c7bddd6b4115de5549e4fd5a4 Mon Sep 17 00:00:00 2001 From: matthew <1123957599@qq.com> Date: Wed, 3 Apr 2024 22:23:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=A4=9A?= =?UTF-8?q?=E9=87=8D=E8=83=8C=E5=8C=85=20Python=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../背包问题理论基础多重背包.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/背包问题理论基础多重背包.md b/problems/背包问题理论基础多重背包.md index 5d6440e3..29f157fb 100644 --- a/problems/背包问题理论基础多重背包.md +++ b/problems/背包问题理论基础多重背包.md @@ -204,6 +204,29 @@ class multi_pack{ ``` ### Python: +```python + +C, N = input().split(" ") +C, N = int(C), int(N) + +# value数组需要判断一下非空不然过不了 +weights = [int(x) for x in input().split(" ")] +values = [int(x) for x in input().split(" ") if x] +nums = [int(x) for x in input().split(" ")] + +dp = [0] * (C + 1) +# 遍历背包容量 +for i in range(N): + for j in range(C, weights[i] - 1, -1): + for k in range(1, nums[i] + 1): + # 遍历 k,如果已经大于背包容量直接跳出循环 + if k * weights[i] > j: + break + dp[j] = max(dp[j], dp[j - weights[i] * k] + values[i] * k) +print(dp[-1]) + +``` + ### Go: