我是 Python 编码新手,需要帮助解决具有多个垃圾箱(4 个垃圾箱)和约束的无界背包问题。
- 这些箱子的重量限制分别为 10.5、10.5、7 和 7。
- 每个箱子只能装满某些物品。例如,仓 0 只能填充项目 0-9,仓 1 只能填充项目 10-19,等等。
- 该算法递归运行,直到达到总权重限制 3000。
我已经修改了 or-tools 中可用的代码,如下所示。输出非常接近我的要求,但我在第 2 项和第 3 项上遇到了问题。
from ortools.linear_solver import pywraplp
def main():
data = {}
data['weights'] = [
0.95,0.31,0.95,0.95,0.95,0.95,0.95,0.95,0.95,0.75,0.95,0.78,0.45,1.00,1.00,1.00,0.19,1.00,1.00,0.50,3.00,3.00,3.00,0.75,
1.25,5.00,3.00,1.00,3.00,1.00,1.00,0.63,3.00,1.00,0.55,1.00,1.00,0.75,0.67,0.38
]
data['values'] = [
0.8554,0.7855,0.7406,0.7282,0.7855,0.8653,0.8529,0.9177,0.8329,0.9077,0.7706,0.8928,0.8354,0.9077,0.8379,0.8055,0.8778,
0.8778,0.9252,0.9501,0.9451,0.9377,0.9252,0.9102,0.9252,0.9476,0.9426,0.9476,0.9377,0.9302,0.9401,0.8579,0.8678,0.8903,
0.8853,0.8105,0.9077,0.9152,0.9152,0.8579
]
assert len(data['weights']) == len(data['values'])
data['num_items'] = len(data['weights'])
data['all_items'] = range(data['num_items'])
data['bin_capacities'] = [10.5, 10.5, 7, 7]
data['num_bins'] = len(data['bin_capacities'])
data['all_bins'] = range(data['num_bins'])
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver('SCIP')
if solver is None:
print('SCIP solver unavailable.')
return
# Variables.
# x[i, b] = 1 if item i is packed in bin b.
x = {}
for i in data['all_items']:
for b in data['all_bins']:
x[i, b] = solver.BoolVar(f'x_{i}_{b}')
# Constraints.
# Each item is assigned to at most one bin.
for i in data['all_items']:
solver.Add(sum(x[i, b] for b in data['all_bins']) <= 1)
# The amount packed in each bin cannot exceed its capacity.
for b in data['all_bins']:
solver.Add(
sum(x[i, b] * data['weights'][i]
for i in data['all_items']) <= data['bin_capacities'][b])
# Objective.
# Maximize total value of packed items.
objective = solver.Objective()
for i in data['all_items']:
for b in data['all_bins']:
objective.SetCoefficient(x[i, b], data['values'][i])
objective.SetMaximization()
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
print(f'Total packed value: {objective.Value()}')
total_weight = 0
for b in data['all_bins']:
print(f'Bin {b}')
bin_weight = 0
bin_value = 0
for i in data['all_items']:
if x[i, b].solution_value() > 0:
print(
f"Item {i} weight: {data['weights'][i]} value: {data['values'][i]}"
)
bin_weight += data['weights'][i]
bin_value += data['values'][i]
print(f'Packed bin weight: {bin_weight}')
print(f'Packed bin value: {bin_value}\n')
total_weight += bin_weight
print(f'Total packed weight: {total_weight}')
else:
print('The problem does not have an optimal solution.')
if __name__ == '__main__':
main()