Skip to content

Commit fda18c0

Browse files
committed
添加 背包问题理论基础多重背包 Python解法
1 parent 6dd9d11 commit fda18c0

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

problems/背包问题理论基础多重背包.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,29 @@ class multi_pack{
204204
```
205205
### Python:
206206

207+
```python
208+
209+
C, N = input().split(" ")
210+
C, N = int(C), int(N)
211+
212+
# value数组需要判断一下非空不然过不了
213+
weights = [int(x) for x in input().split(" ")]
214+
values = [int(x) for x in input().split(" ") if x]
215+
nums = [int(x) for x in input().split(" ")]
216+
217+
dp = [0] * (C + 1)
218+
# 遍历背包容量
219+
for i in range(N):
220+
for j in range(C, weights[i] - 1, -1):
221+
for k in range(1, nums[i] + 1):
222+
# 遍历 k,如果已经大于背包容量直接跳出循环
223+
if k * weights[i] > j:
224+
break
225+
dp[j] = max(dp[j], dp[j - weights[i] * k] + values[i] * k)
226+
print(dp[-1])
227+
228+
```
229+
207230
### Go:
208231

209232

0 commit comments

Comments
 (0)