(๑•͈ᴗ•͈)❀送花给你

01背包 分支限界法

分支限界法

回溯法:找出满足约束条件的所有可行解,深度优先方式搜索解

分支限界:找出满足约束条件的最优解,广度优先/最小耗费优先方式搜索解

参考:https://blog.csdn.net/weixin_44307065/article/details/106465378

import queue
w=[2,2,6,5,4]  #物品i的重量   i对应物品下标   [2,2,6,5,4]
v=[6,3,5,4,6]  #物品i的价值    i对应物品下标   [6,3,5,4,6]
C=10   #背包容量为10
x=[0,0,0,0,0]   #物品i装入背包的份额 0表示物品不装入背包  1表示完全装入背包
#将物品按单位价值从大到小排序  返回数组y:元素为排序后的物品下标
def Sort():
    vi={}
    for i in range(len(w)):
        vi[i]=v[i]/w[i]
    vi=sorted(vi.items(), key=lambda kv: (kv[1], kv[0]),reverse=True)
    result=[]
    for key,value in vi:
        result.append(key)
    return result
# 使用heapq实现优先队列
#定义一个可比较对象
class CompareAble:
    def __init__(self,priority,value):
        self.priority = priority
        self.value=value

    def __lt__(self, other):
        if self.priority >= other.priority:
            return False
        else:
            return True
E= {'parent':None,'Lchild':None}
q = queue.PriorityQueue()
def AddLiveNode(up,cp,cw,ch,lev):
    node={'parent':E,#指向扩展节点
          'Lchild':ch
          }
    heapnode={'uprofit':up,
            'profit':cp,
           'weight':cw,
            'level':lev,
           'ptr':node
    }
    q.put(CompareAble(heapnode['uprofit'],heapnode))
def Func5():
    vi=Sort()
    n=len(w)
    bestx=[0 for i in range(n)]
    i=0
    cw=cp=0  #cw已经用的容量  cp已经算入的价值
    up=Get_bound(0,10,cp)
    bestp=0#当前最优值
    z1=0
    while i<n:
        wt=cw+w[vi[i]]  #已用容量+i的容量
        if(wt<=C):  #左儿子节点为可行节点
            if(cp+v[vi[i]]>bestp):
                bestp=cp+v[vi[i]]
            AddLiveNode(up,cp+v[vi[i]],cw+w[vi[i]],True,i+1)
        up=Get_bound(i,C-cw,cp)
        if(up>=bestp):#右子树可能含有最优解
            AddLiveNode(up,cp,cw,False,i+1)
        heapnode=q.get().value#q中uprofit最大的node
        E=heapnode['ptr']
        cw=heapnode['weight']
        up = heapnode['uprofit']
        cp = heapnode['profit']
        i = heapnode['level']
    return bestp#返回最大总价值
posted @ 2021-10-13 21:40  胸前小红花  阅读(279)  评论(0)    收藏  举报