class Problems_Backpack(object):
def ZeroOnePack(self,N,V,Weight,value):
'''
0-1 背包问题(即每个物品只取一次或者不取)
:Param N 物品的个数 如 N=5
:Param V 背包的总容量,如 V=15
:Param weight 每个物品的重量数组 weight = [5,4,7,2,6]
:Param value 每个物品的机制数组表示,values = [12,3,10,3,6]
:return 返回最大的总价值
'''
# 初始化f[N+1][V+1]为0,f[i][j]表示的是前i件物品放入一个容量为j的背包可以获得的最大价值
f = [[0 for col in range(V+1)] for row in range(N+1)]
# for _ in f:
# print(_)
for i in range(1,N+1):
for j in range(1,V+1):
if j < Weight[i-1]: # 当总容量j小于商品i的重量时,直接不考虑商品
f[i][j] = f[i-1][j]
else:
# 由于weight,Value数组的下标是从0开始,第i个商品的重量为Weight[i-1],价值为Value[i-1]
f[i][j] = max(f[i-1][j],f[i-1][j-Weight[i-1]]+value[i-1]) # 状态方程
max_values = f[N][V]
for _ in f:
print(_)
return max_values
def CompletePack(self,N,V,weight,value):
'''
完全背包问题(每个物品可以无限次取)
'''
# 初始化f[N+1][V+1]矩阵为0
f = [[0 for col in range(V+1)] for row in range(N+1)]
for i in range(1,N+1):
for j in range(1,V+1):
# 注意由于weight,value数组下标是0开始,所以第i件商品的重量和价值分别是weight[i-1],values[i-1]
# j/weight[i-1]表示容量为j时,第i件商品可以取多少次
f[i][j] = f[i-1][j] # 初始取k=0时为最大,下面的循环是把取了k个物品i能获得的最大价值f[i][j]
for k in range(j//weight[i-1]+1):
if f[i][j] < f[i-1][j-k*weight[i-1]]+k*value[i-1]:
f[i][j] = f[i-1][j-k*weight[i-1]+k*weight[i-1]]+k*value[i-1] # 状态方程
max_value = f[N][V]
for i in f:
print(i)
return max_value
def MultiplePack(self,N,V,weight,value,num):
"""
多重背包问题(每个物品都有次数限制)
:param num: 每个物品的个数限制,如num=[2,4,1,5,3]
"""
f = [[0 for col in range(V + 1)] for row in range(N + 1)]
for i in range(1,N+1):
for j in range(1,V+1):
# 对物品i最多能取得次数是j//wight[i-1]与num[i-1]中较小的
min_num = min(j//weight[i-1],num[i-1])
f[i][j] = f[i-1][j] # 初始取k=0为最大,下面的循环是把取了k个物品i能获取的最大价值赋给f[i][j]
for k in range(min_num+1):
if f[i][j] < f[i-1][j-k*weight[i-1]]+k*value[i-1]:
f[i][j] = f[i-1][j-k*weight[i-1]]+k*value[i-1]
max_value = f[N][V]
for i in f:
print(i)
return max_value
weight = [5,4,7,2,6]
values = [12,3,10,3,6]
sol = Problems_Backpack()
num = [2,4,1,5,3]
print('0-1背包问题:',sol.ZeroOnePack(5,15,weight,values))
print('完全背包问题:',sol.CompletePack(5,15,weight,values))
print('多重背包问题:',sol.MultiplePack(5,15,weight,values,num))