我尝试用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)
我有两个问题:
我发现可以用
priority-queue
优化它一般来说,CS理论家发现分支定界算法极难分析:参见例如here的一些讨论。您可以始终使用完整的枚举边界,这通常很容易计算,但通常也非常宽松。在
相关问题 更多 >
编程相关推荐