0-1背包问题算法详解及实现
#-*- coding:utf-8 -*-
import numpy as np
def package1(w,v,c,n):#求取m和choose函数
m=np.zeros((n+1,c+1),dtype=int)
choose=np.zeros((n+1,c+1),dtype=bool)
for j in range(c,0,-1):
if j>=w[n-1]:
m[n,j]=v[n-1]
choose[n, j] = 1
else:
m[n, j]=0
choose[n, j] = 0
for i in range(n-1,0,-1):
for j in range(c,0,-1):
if j<w[i-1]:
m[i,j]=m[i+1,j]
choose[i,j]=0
else:
if m[i+1,j]>m[i+1,j-w[i-1]]+v[i-1]:
m[i, j]=m[i+1,j]
choose[i, j] = 0
else:
m[i, j]=m[i+1,j-w[i-1]]+v[i-1]
choose[i, j] = 1
return m,choose
def output(m, choose,c,n):#构造最优解函数
result = []
j = c
for i in range(1,n+1):
result.append(choose[i, j])
j = j - w[i - 1] * choose[i, j]
i = i + 1
print 'max value:',m[1, c]
print 'choose result:',result
if __name__=='__main__':
w=[4,3,2]
v=[5,2,1]
m, choose=package1(w,v,6,3)
output(m, choose, 6, 3)
运行结果:
max value: 6
choose result: [True, False, True]
希望以上讲解能够帮到大家,下一篇会是对此算法进行一个优化,有兴趣的可以一起学习。
由于博客园不好编辑公式,因此写好了截图的,以上为原创,欢迎大家指正
where there is a will,there is a way where there is a will,there is a way
where there is a will,there is a way where there is a will,there is a way
where there is a will,there is a way where there is a will,there is a way
where there is a will,there is a way where there is a will,there is a way
where there is a will,there is a way where there is a will,there is a way
where there is a will,there is a way where there is a will,there is a way
where there is a will,there is a way where there is a will,there is a way