[python dynamic programming/recursion] the maximum value of treasures

Problem Description

  • The thief sneaks into the museum, and there are 5 treasures in front of him, each with weight and value. The thief’s backpack can only attach 20 kilograms. How to choose the treasure, which one has the highest total value?
  • The weight and value correspondence table of treasures is as follows:
item weight value
1 2 3
2 3 4
3 4 8
4 5 8
5 9 10

problem solving ideas

  • m ( i , W ) m(i, W) m(i,W ) marked as:
  • i ( 1 < = i < = 5 ) i(1<=i<=5) i(1<=i<=5 ) Among the treasures, the combinationdoes not exceedW ( 1 < = W < = 20 ) W(1<=W<=20)W(1<=W<=20 ) weight, getthe maximum value
  • m ( i , W ) m(i,W) m(i,W ) ought to bem ( i − 1 , W ) m(i-1,W)m(i1,W) m ( i − 1 , W − W i ) + V i m(i-1, W-W_{i})+V_{i} m(i1,WWi)+Vi, the maximum of both
  • From m ( 1 , 1 ) m(1,1)m(1,1 ) start counting tillm(5,5) m(5,5)m(5,5)
    $$

Code

def maxValue(max_w):
    """
    :max_w: 最大携带重量
    """
    # 宝物的价值和重量
    tr = [None, {
    
    'w':2, 'v':3}, {
    
    'w':3, 'v':4},
                {
    
    'w':4, 'v':8}, {
    
    'w':5, 'v':8},
                {
    
    'w':9, 'v':10}]

    # 初始化二维表格m[(i,w)]
    # 表示前i宝物中,最大重量w的组合,所得到的最大价值
    # 当i什么都不取,或者w的上线为0,价值均为0
    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:  # 装不下第i个宝物
                m[(i,w)] = m[(i-1, w)] # 不装第i个宝物
            else:
                m[(i,w)] = max(m[(i-1, w)], m[(i-1,w-tr[i]['w'])] + tr[i]['v'])
    return m[(len(tr)-1, max_w)]

maxValue(20)

Recursive thinking - code implementation

The "Three Laws" of Recursive Algorithms

  • A recursive algorithm must have a basic end condition
  • The recursive algorithm must reduce the scale, change the state, and evolve to the basic end condition
  • A recursive algorithm must call itself
# 宝物的重量和价值
tr = {
    
    (2,3), (3,4), (4,8),(5,8), (9,10)}

# 大盗的最大承重
max_w = 20

# 初始化记忆化表格m
# key是(宝物组合,最大重量),value是最大价值
m = {
    
    }

def thief(tr, w):
	if tr == set() or w == 0:
		m[tuple(tr), w] = 0  # tuple是key的要求
		return 0
	elif (tuple(tr), w) in m:
		return m[tuple(tr), w]
	else:
		vmax = 0
		for t in tr:
			if t[0] <= w:
				# 逐个从集合中去掉某个宝物,递归调用
				# 选出所有价值中的最大值
				v = thief(tr-{
    
    t}, w-t[0]) + t[1]
				vmax = max(vmax, v)
		m[tuple(tr), w] = vmax
		return vmax

print(thief(tr, max_w))

Guess you like

Origin blog.csdn.net/qq_38734327/article/details/132353855