问题介绍见:网络流问题:交通调度、仓储运输 (aliyun.com)
import gurobipy as gb
from gurobipy import *
# 参数
start= ["a"]
mid_point = ["b","c","d","e","f"]
end = ["g"]
arcs, capacity = gb.multidict({
("a","b"):50,
("a","c"):100,
("b","d"):40,
("b","e"):20,
("c","d"):60,
("c","f"):20,
("d","e"):50,
("d","f"):60,
("e","g"):70,
("f","g"):70
})
# model
model = gb.Model()
# decision var
flow = model.addVars(arcs, lb = 0, vtype = GRB.INTEGER, name = "flow")
# constraints
# mid_points constraints
model.addConstrs((flow.sum("*", mid) == flow.sum(mid, "*") for mid in mid_point), name = "mid_point constrains")
# capacity constraints
model.addConstrs((flow[arc] <= capacity[arc] for arc in arcs), name = "capacity constraints")
# model.addConsts((flow.select(arc) <= capacity.select(arc) for arc in arcs), name = "capacity constraints")
# objective
obj = flow.sum("*", "g")
model.setObjective(obj, GRB.MAXIMIZE) #默认是求最小值
model.optimize()
# print(flow)
print(model.objVal) # 打印目标函数值
for v in model.getVars():
# 打印最终解中的决策变量
print(v.x)