Gurobi建模求解简单背包问题

问题:

Gurobi建模求解简单背包问题_第1张图片

代码:

 

# -*- coding : utf-8 -*-
# @Time      : 2022/5/10 10:32
# @Author    : wkb
from gurobipy import *
import time

x = {}
model = Model("EMAPLE")
# define the varaibles
for i in range(4):
    x[i] = model.addVar(0,1,vtype=GRB.BINARY,name="x{0}".format(i))
# set the objective
c =[8,11,6,4]
expr = LinExpr(0)
for i in range(4):
    expr.addTerms(c[i],x[i])
model.setObjective(expr,sense=GRB.MAXIMIZE)

# add the constrains_1
expr = LinExpr(0)
a = [5,7,4,3]
for i in range(4):
    expr.addTerms(a[i],x[i])
model.addConstr(expr <= 14,name="c_1")

model.write("example.lp")
#solution
start_time = time.time()
model.setParam("Thread",8)
model.setParam("TimeLimit",10)
model.optimize()
end_time = time.time()
cpu_time = end_time-start_time
if model.status == GRB.OPTIMAL:
    s_x = {}
    for key in x.keys():
        s_x[key] = x[key].x
    print("x = ",s_x)

    obj = model.getObjective()
    print("obj = ",obj.getValue())

    print("cpu = %.2f sec"%cpu_time)



你可能感兴趣的:(python)