我正在尝试解决最小的图形着色问题。我想解决这个问题。我正在遵循本文中概述的解决方案:
https://manas.tech/blog/2010/09/16/modelling-graph-coloring-with-integer-linear-programming.html
我认为我定义j的方式可能存在问题:
j = int(first_line [0])
我将其定义为节点数,因为我认为既然x和w是二进制变量,它们可能具有最大维数,但是我在下面定义的约束将迫使它们的条目数最少为1。谁能告诉我是否在下面正确设置了问题,还是需要让我的j值从最小值开始并增加?如果是这样,有人可以建议我应该如何设置我的j值?我还在学习cvxpy。
此帖子还与我之前发表的帖子有关:
Define CVXPY variables for graph coloring problem
代码:
input_data
# '4 3\n0 1\n1 2\n1 3\n'
# parse the input
lines = input_data.split('\n')
first_line = lines[0].split()
node_count = int(first_line[0])
edge_count = int(first_line[1])
edges = []
for i in range(1, edge_count + 1):
line = lines[i]
parts = line.split()
edges.append((int(parts[0]), int(parts[1])))
import numpy as np
import cvxpy
from collections import namedtuple
# binary variable if at least one node is color j
j=int(first_line[0])
# w=1 if at least one node has color j
w = cvxpy.Variable(j, boolean=True)
# x=1 if node i is color j
x = cvxpy.Variable((j,j), boolean=True)
# constraints
# 1 color per node
node_color=cvxpy.sum(x,axis=1)==1
# for adjacent nodes at most 1 node has color
diff_col = []
for edge in edges:
for k in range(node_count):
diff_col += [
x[edge[0],k]+x[edge[1],k]<=1
]
# w is upper bound for color of node x<=w
upper_bound = []
for i in range(j):
for k in range(j):
upper_bound += [
x[k,i]<=w[i]
]
# constraints
constraints=[node_color]+diff_col+upper_bound
# Objective function
# minimize number of colors needed
obj=cvxpy.sum(w,axis=0)
# solving problem
# cvxpy must be passed as a list
graph_problem = cvxpy.Problem(cvxpy.Minimize(obj), constraints)
# Solving the problem
graph_problem.solve(solver=cvxpy.GLPK_MI)
value2=int(graph_problem.solve(solver=cvxpy.GLPK_MI))
taken2=[int(i) for i in w.value.tolist()]
# prepare the solution in the specified output format
output_data2 = str(value2) + ' ' + str(0) + '\n'
output_data2 += ' '.join(map(str, taken2))
# Objective function after solving
value2
# 2
# Solution node colors
x.value.tolist()
# [[1.0, 0.0, 0.0, 0.0],
# [0.0, 0.0, 1.0, 0.0],
# [1.0, 0.0, 0.0, 0.0],
# [1.0, 0.0, 0.0, 0.0]]