[英]exact gurobi solver for chromatic number of coloring problem [error in the objective]
我試圖通過在 lp 設置中使用 gurobi 來解決着色問題。 但是,我做錯了什么,但不到底是什么。
`!pip 安裝 gurobipy'
import networkx as nx
import gurobipy as gp
from gurobipy import *
import networkx as nx
# create test graph
n = 70
p = 0.6
G = nx.erdos_renyi_graph(n, p)
nx.draw(G, with_labels = True)
# compute chromatic number -- ILP solve
m = gp.Model('chrom_num', env =e)
# get maximum number of variables necessary
k = max(dict(nx.degree(G)).values()) + 1
TEST= range(k)
# create k binary variables, y_0 ... y_{k-1} to indicate whether color k is used
y = []
for j in range(k):
y.append(m.addVar(vtype=gp.GRB.BINARY, name='y_%d' % j, obj=1))
# create n * k binary variables, x_{l,j} that is 1 if node l is colored with j
x = []
for l in range(n):
x.append([])
for j in range(k):
x[-1].append(m.addVar(vtype=gp.GRB.BINARY, name='x_%d_%d' % (l, j), obj=0))
# objective function is minimize colors used --> sum of y_0 ... y_{k-1}
m.setObjective(gp.quicksum(y[j] for j in TEST), gp.GRB.MINIMIZE)
m.update()
# add constraint -- each node gets exactly one color (sum of colors used is 1)
for u in range(n):
m.addConstr(gp.quicksum(x[u]) == 1, name='NC_%d')
# add constraint -- keep track of colors used (y_j is set high if any time j is used)
for l in range(n):
for j in range(k):
m.addConstr(x[u][j] <= y[j], name='SH_%d_%d')
# add constraint -- adjacent nodes have different colors
for u in range(n):
for v in G[u]:
if v > u:
for j in range(k):
m.addConstr(x[u][j] + x[v][j] <= 1, name='ADJ_%d_%d_COL_%d')
# update model, solve, return the chromatic number
m.update()
m.optimize()
chrom_num = m.objVal
通過為圖形着色問題添加額外的約束已經得到了答案。
for u in range(n):
for v in G[u]:
if v > u:
for j in range(k):
m.addConstr(x[u][j] + x[v][j] <= y[j], name='ADJ_%d_%d_COL_%d')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.