or-tools cp-sat CpModel.AddAbsEquality
1 示例程序
链接: 官方文档
from ortools.sat.python import cp_model
def abs_equality_example():
# 创建一个 CP-SAT 模型
model = cp_model.CpModel()
# 创建变量
x = model.NewIntVar(-10, 10, 'x')
y = model.NewIntVar(-10, 10, 'y')
z = model.NewIntVar(0, 20, 'z') # 绝对差的绝对值将存储在这里
# 添加绝对等式约束:|x - y| = z
model.AddAbsEquality(z, x - y)
# 创建求解器
solver = cp_model.CpSolver()
# 解决问题
status = solver.Solve(model)
# 打印解
if status == cp_model.FEASIBLE:
print("找到解:")
print("x =", solver.Value(x))
print("y =", solver.Value(y))
print("z =", solver.Value(z))
else:
print("未找到解.")
# 调用示例函数
abs_equality_example()