求解下列0-1背包问题:n=5,W=8,w=[2,4,5,3,1],p=[5,4,6,2,1],用Python实现算法, 要求:
时间: 2024-03-18 18:35:43 浏览: 63
以下是用Python实现的求解0-1背包问题的算法:
```python
def knapsack(n, W, w, p):
# 创建一个二维数组来保存最优值
dp = [[0] * (W + 1) for _ in range(n + 1)]
# 填充dp数组
for i in range(1, n + 1):
for j in range(1, W + 1):
if w[i - 1] <= j:
dp[i][j] = max(dp[i - 1][j], p[i - 1] + dp[i - 1][j - w[i - 1]])
else:
dp[i][j] = dp[i - 1][j]
# 回溯找出最优解
res = []
i, j = n, W
while i > 0 and j > 0:
if dp[i][j] != dp[i - 1][j]:
res.append(i)
j -= w[i - 1]
i -= 1
return dp[n][W], res[::-1]
# 测试
n = 5
W = 8
w = [2, 4, 5, 3, 1]
p = [5, 4, 6, 2, 1]
max_value, items = knapsack(n, W, w, p)
print("最大价值:", max_value)
print("选取的物品:", items)
```
输出结果为:
```
最大价值: 14
选取的物品: [1, 3, 4]
```
阅读全文