1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| from queue import PriorityQueue
class SSTNode:
def __init__(self, level, profit, weight): self.level = level self.profit = profit self.weight = weight self.bound = 0
def print(self): print(self.level, self.profit, self.weight, self.bound)
def bound(u, p, w): n = len(p) - 1 if u.weight >= W: return 0 else: result = u.profit j = u.level + 1 totweight = u.weight while j <= n and totweight + w[j] <= W: totweight += w[j] result += p[j] j += 1 k = j if k <= n: result += (W - totweight) * p[k] / w[k] return result
def knapsack4(p, w, W): PQ = PriorityQueue() v = SSTNode(0, 0, 0) maxprofit = 0 v.bound = bound(v, p, w) PQ.put((-v.bound, v)) while not PQ.empty(): v = PQ.get()[1] print("POP:", end="") v.print() if v.bound > maxprofit: level = v.level + 1 weight = v.weight + w[level] profit = v.profit + p[level] u = SSTNode(level, profit, weight) if u.weight <= W and u.profit > maxprofit: maxprofit = u.profit u.bound = bound(u, p, w) print("\tPUT:", end="") u.print() if u.bound > maxprofit: PQ.put((-u.bound, u)) print("\t\tYES") u = SSTNode(level, v.profit, v.weight) u.bound = bound(u, p, w) print("\tPUT:", end="") u.print() if u.bound > maxprofit: PQ.put((-u.bound, u)) print("\t\tYES") return maxprofit
|