【问题标题】:What's the time complexity of branch and bound approach to knapsack背包分支定界法的时间复杂度是多少
【发布时间】: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


【解决方案1】:

作为一般规则,CS 理论家发现分支定界算法极难分析:参见例如here 进行一些讨论。您始终可以采用全枚举界限,这通常很容易计算——但它通常也非常松散。

【讨论】:

    【解决方案2】:

    我发现它可以用priority-queue优化

    def knapsack(vw, limit):
        maxValue = 0
        PQ = [[-bound(0, 0, 0), 0, 0, 0]]
        while PQ:
            b, v, w, j = heappop(PQ)
            if b <= -maxValue:
                if w + vw[j][1] <= limit:
                    maxValue = max(maxValue, v + vw[j][0])
                    heappush(PQ, [-bound(v+vw[j][0], w+vw[j][1], j+1),
                                        v+vw[j][0], w+vw[j][1], j+1])
                if j < len(vw) - 1:
                    heappush(PQ, [-bound(v, w, j+1), v, w, j+1])
        return maxValue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2018-01-18
      • 2020-01-26
      • 2011-05-14
      • 1970-01-01
      相关资源
      最近更新 更多