Dynamic programming---backpack problem
weight=[0,1,3,4,8]
value=[0,4,3,2,5]
c=9
m = [[0]*10 for i in range(10)]
def min(x,y):
if x < y:
return x
else:
return y
def package(weight, value, n, total):
#the items that you can choose :i, i+1, ...,n
#the volume of the package:j
cur_weight = min(weight[n]-1, total)
for j in range(1, weight[n]):
m[n][j]=0
for j in range(weight[n], total+1):
m[n][j]=weight[n]
i = n-1
while i >0:
cur_weight = min(weight[i]-1, total)
for j in range(1, weight[i]):
m[i][j]=m[i+1][j]
for j in range(weight[i], total+1):
m[i][j] = max(m[i+1][j], m[i+1][j-cur_weight]+value[i])
i = i-1
package(weight, value, 4, 5)
print m[1][5]

浙公网安备 33010602011771号