问题描述
例如,当我在轮班计划中遇到以下问题时,如何使用SolveWithSolutionCallback方法指定要打印的解决方案?
Solution 13,time = 37.58 s,objective = 82
Solution 14,time = 37.71 s,objective = 81
Solution 15,time = 37.87 s,objective = 80
Solution 16,time = 37.96 s,objective = 76
比方说,我想看看解决方案13和14产生了什么,有什么办法吗?
解决方法
您可以将解决方案存储在回调的列表中,或将其记录到文件中,等等:
from ortools.sat.python import cp_model
class Callback(cp_model.CpSolverSolutionCallback):
def __init__(self,variables):
cp_model.CpSolverSolutionCallback.__init__(self)
self.variables = variables
self.solutions = []
def on_solution_callback(self):
self.solutions.append([self.Value(v) for v in self.variables])
if __name__ == "__main__":
model = cp_model.CpModel()
num_vals = 3
x = model.NewIntVar(0,num_vals - 1,"x")
y = model.NewIntVar(0,"y")
z = model.NewIntVar(0,"z")
model.Add(x != y)
solver = cp_model.CpSolver()
callback = Callback([x,y,z])
solver.SearchForAllSolutions(model,callback)
print(callback.solutions)