01背包问题python实现

可以记录路径,有时间再完善

# -*- coding:utf-8 -*-
def bag(n, c, w, v):
    res = [[0 for j in range(c + 1)] for i in range(n + 1)]
    for j in range(c + 1):
        res[0][j] = 0
    for i in range(1, n + 1):
        for j in range(1, c + 1):
            res[i][j] = res[i - 1][j]
            if j >= w[i - 1] and res[i][j] < res[i - 1][j - w[i - 1]] + v[i - 1]:
                res[i][j] = res[i - 1][j - w[i - 1]] + v[i - 1]
    print res
    return res


def show(n, c, w, res):
    print '最大价值为:', res[n][c]
    x = [False for i in range(n)]
    j = c
    i = n
    while i > 0:
        if res[i][j] > res[i - 1][j]:
            x[i - 1] = True
            j -= w[i - 1]
            i -= 1
        else:
            i -= 1
    print '选择的物品为:'
    for i in range(n):
        if x[i]:
            print '第', i, '个'

if __name__ == '__main__':
    n = 5
    c = 17
    w = [2, 2, 6, 5, 4]
    v = [2, 2, 6, 5, 4]
    res = bag(n, c, w, v)
    show(n, c, w, res)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用队列式分支限界法解决01背包问题Python实现: ```python from queue import PriorityQueue class Node: def __init__(self, level, profit, weight, bound): self.level = level self.profit = profit self.weight = weight self.bound = bound def __lt__(self, other): return self.bound > other.bound def bound(node, n, W, p, w): if node.weight >= W: return 0 else: result = node.profit j = node.level + 1 totweight = node.weight while j <= n and totweight + w[j] <= W: totweight += w[j] result += p[j] j += 1 if j <= n: result += (W - totweight) * p[j] / w[j] return result def knapsack(n, W, p, w): q = PriorityQueue() v = Node(0, 0, 0, 0) u = Node(0, p[1], w[1], 0) maxprofit = 0 u.bound = bound(u, n, W, p, w) q.put(u) while not q.empty(): u = q.get() if u.bound > maxprofit: v.level = u.level + 1 v.weight = u.weight + w[v.level] v.profit = u.profit + p[v.level] if v.weight <= W and v.profit > maxprofit: maxprofit = v.profit v.bound = bound(v, n, W, p, w) if v.bound > maxprofit: q.put(v) v.weight = u.weight v.profit = u.profit v.bound = bound(v, n, W, p, w) if v.bound > maxprofit: q.put(v) return maxprofit # Sample usage n = 5 W = 10 p = [0, 40, 50, 100, 95, 30] w = [0, 2, 3, 5, 4, 8] print(knapsack(n, W, p, w)) # Output: 235 ``` 在这个实现中,我们使用了Python的`PriorityQueue`数据结构来维护未扩展节点的队列。在每次从队列中获取节点时,我们计算其上界,如果上界大于当前已知的最大收益,则将其扩展并将其子节点加入队列中。我们通过排序队列来确保我们总是优先考虑具有最高上界的节点。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值