#-*- coding:utf-8 -*-算法
import numpy as npapp
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):spa
if j>=w[n-1]:blog
m[n,j]=v[n-1]utf-8
choose[n, j] = 1博客
else:import
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