您的位置:首页 > 其它

完全背包问题

2013-10-08 08:21 225 查看
一:问题:

有N种物品和一个容量为V的背包,每种物品都有无限件可用。第i种物品的费用是c[i],价值是w[i]。 求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大

二:完全背包问题与01背包问题的唯一区别在于每个物品可以重复使用。因此不用像01背包问题使用二位数组,利用一个维来避免物品重复

三:伪代码

for(int i = 0 ; i < T ; i++)

for(int v = c[i] ;v <= V ;v++)

f[v] = max(f[v] , f[v - c[i]] + w[i]) ;

四:实现

#!/usr/bin/python
m = int(raw_input("get m as the max bag size:"))
n = int(raw_input("get n as the goods tots:"))

print("bag max store: %d, goods tots: %d" % (m, n))
table = [0]*(m+1)

p = [0]
w = [0]

for i in range(1, n+1):
    weigth = int(raw_input("get weigth:"))
    value =  int(raw_input("get val:"))
    w.append(weigth)
    p.append(value)

print p
print w
#print table

for row in range(1, n+1):
    for col in range(1, m+1):
        if(w[row] <= col and table[col - w[row]] + p[row] > table[col]):
                            table[col] = table[col - w[row]] + p[row]

print table
print "max value can store:" + str(table[m])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: