Python 实现0-1背包

代码:

import numpy as np
c=10             #背包容量
w=[2,2,6,5,4]    #物品重量
v=[5,3,5,4,6]     #物品价值
flag =[0,0,0,0,0]
m=np.zeros([5,11],int)           #用来保存 5x11的矩阵


for j in range(c+1):         #初始化第一行
    if(w[0]<=j):
        m[0][j]=v[0]
        flag[0] = 1
for i in range(1,5):
    for j in range(c+1):
        if (j<w[i]):
            m[i][j]=m[i-1][j]
        else:
            if(m[i-1][j-w[i]]+v[i]>m[i-1][j]):
                m[i][j] = m[i-1][j-w[i]]+v[i]
            else:
                m[i][j]=m[i-1][j]
print("最大价值为:",m[len(w)-1][c])

for i in range(4,0,-1):
    if(m[i][c]>m[i-1][c]):
        flag[i] = 1
        c = c -w[i]
    else:
        flag[i] = 0
print("选择的物品有:",end = ' ')
for i in range(len(flag)):
    if(flag[i]==1):
        print(i,end =' ')

 

posted @ 2018-04-09 13:06  夜雨最萌  阅读(1235)  评论(0编辑  收藏  举报