我必须用这些限制来解决运输问题(A是供应行,B是需求列,矩阵有运输价格):
A \ B | 6 | 15 | 7 | 8 | 8 |
---|---|---|---|---|---|
17 | 10 | 8 | 5 | 9 | 16 |
8 | 4 | 3 | 4 | 11 | 12 |
10 | 5 | 10 | 29 | 7 | 6 |
9 | 9 | 2 | 4 | 1 | 3 |
我已经找到了解决方案,代码工作正常,因为我解决了任务,答案是一样的.括号内是运输量.例如,在第(1,2)项中,我们有10吨运输,价格为每吨8美元=总共80美元.
A \ B | 6 | 15 | 7 | 8 | 8 |
---|---|---|---|---|---|
17 | 10 | (10)\8 | (7)\5 | 9 | 16 |
8 | (3)\4 | (5)\3 | 4 | 11 | 12 |
10 | (3)\5 | 10 | 29 | 7 | (7)\6 |
9 | 9 | 2 | 4 | (8)\1 | (1)\3 |
但是,我的任务有一个限制.我需要用6吨重的卡车来运输.例如,在元素(1,2)中,我必须以每吨8美元的价格交付10吨.这意味着总共80美元,但由于我的限制,这意味着我需要预订2辆卡车并支付120美元.
因此,考虑到这个限制,并使用分支定界法,我需要找到最优解.我该怎么办?
import gurobipy as gp
from gurobipy import GRB
# Define data
supply = [17, 8, 10, 9] # Supply nodes
demand = [6, 15, 7, 8, 8] # Demand nodes
cost = [
[10, 8, 5, 9, 16],
[4, 3, 4, 11, 12],
[5, 10, 29, 7, 6],
[9, 2, 4, 1, 3]
] # Cost of transportation from supply i to demand j
m = gp.Model()
# Define decision variables
flow = m.addVars(len(supply), len(demand), lb=0, vtype=GRB.INTEGER, name="flow")
# Define supply constraints
for i in range(len(supply)):
m.addConstr(gp.quicksum(flow[i, j] for j in range(len(demand))) <= supply[i], name=f"supply_{i}")
# Define demand constraints
for j in range(len(demand)):
m.addConstr(gp.quicksum(flow[i, j] for i in range(len(supply))) >= demand[j], name=f"demand_{j}")
# Define objective function
m.setObjective(gp.quicksum(flow[i, j] * cost[i][j] for i in range(len(supply)) for j in range(len(demand))), sense=GRB.MINIMIZE)
# Solve model
m.optimize()
# Print results
if m.status == GRB.OPTIMAL:
print(f"Optimal solution found with objective value {m.objVal:.2f}")
for i in range(len(supply)):
for j in range(len(demand)):
if flow[i, j].x > 0:
print(f"Flow from supply node {i+1} to demand node {j+1}: {flow[i, j].x:.0f}")
else:
print("No solution found or problem is infeasible.")