Sử dụng thuật toán nhánh và liên kết Tôi đã đánh giá lợi nhuận tối ưu từ một tập hợp các mặt hàng nhất định, nhưng bây giờ tôi muốn tìm hiểu các mặt hàng nào được bao gồm trong giải pháp tối ưu này. Tôi đánh giá giá trị lợi nhuận của ba lô tối ưu như sau (chuyển thể từ here):Tính toán các hạng mục được bao gồm trong chi nhánh và lô hàng bị ràng buộc
import Queue
class Node:
def __init__(self, level, profit, weight):
self.level = level # The level within the tree (depth)
self.profit = profit # The total profit
self.weight = weight # The total weight
def solveKnapsack(weights, profits, knapsackSize):
numItems = len(weights)
queue = Queue.Queue()
root = Node(-1, 0, 0)
queue.put(root)
maxProfit = 0
bound = 0
while not queue.empty():
v = queue.get() # Get the next item on the queue
uLevel = v.level + 1
u = Node(uLevel, v.profit + e[uLevel][1], v.weight + e[uLevel][0])
bound = getBound(u, numItems, knapsackSize, weights, profits)
if u.weight <= knapsackSize and u.profit > maxProfit:
maxProfit = uProfit
if bound > maxProfit:
queue.put(u)
u = Node(uLevel, v.profit, v.weight)
bound = getBound(u, numItems, knapsackSize, weights, profits)
if (bound > maxProfit):
queue.put(u)
return maxProfit
# This is essentially the brute force solution to the fractional knapsack
def getBound(u, numItems, knapsackSize, weight, profit):
if u.weight >= knapsackSize: return 0
else:
upperBound = u.profit
totalWeight = u.weight
j = u.level + 1
while j < numItems and totalWeight + weight[j] <= C:
upperBound += profit[j]
totalWeight += weights[j]
j += 1
if j < numItems:
result += (C - totalWeight) * profit[j]/weight[j]
return upperBound
Vì vậy, thế nào tôi có thể nhận được vật phẩm hình thành giải pháp tối ưu, chứ không phải chỉ là lợi nhuận?
Tôi không chắc chắn điều này sẽ mang đến sự thư giãn tuyến tính tối đa cho các ràng buộc về mặt hàng. – franklin