# 宝物的重量和价值
tr = [None, {'w': 2, 'v': 3}, {'w': 3, 'v': 4},
{'w': 4, 'v': 8}, {'w': 5, 'v': 8},
{'w': 9, 'v': 10}
]
max_w = 20
# 初始化二维表格m{(i, w)}
m = {(i, w): 0 for i in range(len(tr)) for w in range(max_w + 1)}
for i in range(1, len(tr)):
for w in range(1, max_w + 1):
if tr[i]['w'] > w:
m[(i,w)] = m[(i - 1, w)]
else:
m[(i,w)] = max(m[(i-1),w], tr[i]['v'] + m[(i - 1, w - tr[i]['w'])])
# 输出结果
print(m[(len(tr)-1, max_w)])
print(m)
python学习之动态规划解决博物馆大盗问题
最新推荐文章于 2023-07-15 11:32:37 发布