import gurobipy as gp
from gurobipy import GRB
# Input the information of the network
dict_capacity = {(0, 1): 99999,
(1, 2): 70, (1, 3): 100, (1, 4): 90,
(2, 6): 80,
(3, 4): 40, (3, 5): 70,
(4, 5): 40, (4, 6): 100,
(5, 6): 90,
(6, 7): 99999
}
arc, capacity = gp.multidict(dict_capacity)
# Construct the model
m = gp.Model("maxflow")
# Decision variables
X = m.addVars(arc, name='X')
# Add constraints
for i, j in arc:
# The volume of flow cannot exceed the capacity of the arc
m.addConstr(X[i, j] <= capacity[i, j])
if i == 0 or j == 7:
continue
else:
# Flow balance constraint
m.addConstr(X.sum(i, '*') == X.sum('*', i))
# Define the objective function
m.setObjective(X.sum(1, '*'), sense=GRB.MAXIMIZE)
# Solve the model
m.optimize()
# Output the results
print('*' * 60)
print("The objective value is:", m.objVal)
print('The flow in each arc is:')
for i, j in arc:
print("Node %d --> Node %d: %d" % (i, j, X[i, j].x))
控制台输出结果
Using license file C:\Users\86158\gurobi.lic
Gurobi Optimizer version 9.1.1 build v9.1.1rc0 (win64)
Thread count: 4 physical cores, 8 logical processors, using up to 8 threads
Optimize a model with 20 rows, 11 columns and 42 nonzeros
Model fingerprint: 0x43a077e0
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [1e+00, 1e+00]
Bounds range [0e+00, 0e+00]
RHS range [4e+01, 1e+05]
Presolve removed 17 rows and 5 columns
Presolve time: 0.00s
Presolved: 3 rows, 6 columns, 9 nonzeros
Iteration Objective Primal Inf. Dual Inf. Time
0 2.6000000e+02 3.125000e+01 0.000000e+00 0s
3 2.6000000e+02 0.000000e+00 0.000000e+00 0s
Solved in 3 iterations and 0.00 seconds
Optimal objective 2.600000000e+02
************************************************************
The objective value is: 260.0
The flow in each arc is:
Node 0 --> Node 1: 260
Node 1 --> Node 2: 70
Node 1 --> Node 3: 100
Node 1 --> Node 4: 90
Node 2 --> Node 6: 70
Node 3 --> Node 4: 40
Node 3 --> Node 5: 60
Node 4 --> Node 5: 30
Node 4 --> Node 6: 100
Node 5 --> Node 6: 90
Node 6 --> Node 7: 0
Process finished with exit code 0