【发布时间】:2015-11-02 03:12:22
【问题描述】:
我尝试使用Python 实现背包问题的分支定界方法。
def bound(vw, v, w, idx):
if idx >= len(vw) or w > limit:
return -1
else:
while idx < len(vw) and w + vw[idx][1] <= limit:
v, w, idx = v+vw[idx][0], w+vw[idx][1], idx + 1
if idx < len(vw):
v += (limit - w)*vw[idx][0]/(vw[idx][1] * 1.0)
return v
def knapsack(vw, limit, curValue, curWeight, curIndex):
global maxValue
if bound(vw, curValue, curWeight, curIndex) >= maxValue:
if curWeight + vw[curIndex][1] <= limit:
maxValue = max(maxValue, curValue + vw[curIndex][0])
knapsack(vw, limit, curValue + vw[curIndex][0], curWeight + vw[curIndex][1], curIndex+1)
if curIndex < len(vw) - 1:
knapsack(vw, limit, curValue, curWeight, curIndex+1)
return maxValue
maxValue = 0
def test():
with open(sys.argv[1] if len(sys.argv) > 1 else sys.exit(1)) as f:
limit, n = map(int, f.readline().split())
vw = []
for ln in f.readlines():
vl, wl = map(int, ln.split())
vw.append([vl, wl, vl/(wl*1.0)])
knapsack(sorted(vw, key=lambda x: x[2], reverse=True), limit)
这里我有两个问题:
- 以上代码的时间复杂度是多少?
- 上述代码有什么改进或优化吗?
【问题讨论】:
-
我们如何获取选中的项目?如果我们要找出它们,复杂性会增加吗?
-
此代码不起作用。
limit未在bound中定义。
标签: python algorithm knapsack-problem