如何确保某个值是ortools中一组决策变量的成员

问题描述 投票:0回答:1

我想实现约束,以确保某个值是一组决策变量的一部分。所以对于例如令

dv[i]
为一组由
i
索引的决策变量。比如说,域限制在
0-10
之间。我希望应确保值
4
(比如说)是
dv
的成员。

from ortools.sat.python import cp_model as cp

model = cp.CpModel()
dv = [model.NewIntVar(lb=0, ub=10, name = f"dv[{_+1}]") for _ in range(5)]

# this val should be a member of dv
val = 4
linear-programming or-tools mixed-integer-programming cp-sat
1个回答
0
投票

下面是确保预定值是决策变量的成员的一种可能方法。

from ortools.sat.python import cp_model as cp

model = cp.CpModel()
dv = [model.NewIntVar(lb=0, ub=10, name = f"dv[{_+1}]") for _ in range(5)]

val = 4

n = len(dv)
b = [model.NewBoolVar(f"b[{i}]")  for i in range(n)]
cnt_val = model.NewIntVar(lb = 0, ub = len(dv), name = "count_vars")
# below is the purpose of cnt_val variable 
# cnt_val = sum([dv[i] == val for i in range(len(dv))])
for i in range(n):
    model.Add((dv[i] == val)).OnlyEnforceIf(b[i])
    model.Add((dv[i] != val)).OnlyEnforceIf(b[i].Not())
model.Add(cnt_val == sum(b))
# ensure that cnt_val is > 0
model.Add(cnt_val > 0)

model.Maximize(sum(dv))
solver = cp.CpSolver()
status = solver.solve(model)

print([solver.value(dv[i]) for i in range(5)])
# results in : [10, 10, 10, 10, 4]
# no constraints are imposed to place 4 in any specific position
© www.soinside.com 2019 - 2024. All rights reserved.