gurobi python 求解指派问题

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 10:42:22 2018

@author: Hua Deyou
"""

import numpy as np
from gurobipy import *
#系数
c=np.zeros((4,4))
for i in range(4):
    for j in range(4):
        c[i][j]=1+(np.random.randint(100))%7
        print(c[i][j])
#变量
m=Model('assing_problem')
x=[[0 for i in range(4)] for j in range(4)]
for i in range(4):
    for j in range(4):
        x[i][j]=m.addVar(lb=0,ub=1,vtype=GRB.BINARY)
#目标 
obj=LinExpr()
for i in range(4):
    for j in range(4):
        obj+= c[i][j]*x[i][j]

m.setObjective(obj,GRB.MAXIMIZE)
#约束
for i in range(4):
    sum_1=LinExpr()
    sum_2=LinExpr()
    for j in range(4):
        sum_1+=x[i][j]
        sum_2+=x[j][i]
    m.addConstr(sum_1==1)
    m.addConstr(sum_2==1)

#求解    
m.write('assign.lp')
m.optimize()
print('optimal value: %d'%obj.getValue())
for i in range(4):
    for j in range(4):
        if (x[i][j].x>0):
            print('x[%d][%d]=%d'%(i,j,x[i][j].x))

你可能感兴趣的:(python,gurobi)