22 #include "absl/container/flat_hash_set.h" 34 const std::vector<IntegerVariable>& vars) {
40 std::map<IntegerValue, std::vector<Literal>> value_to_literals;
42 for (
const IntegerVariable
var : vars) {
45 value_to_literals[entry.value].push_back(entry.literal);
50 for (
const auto& entry : value_to_literals) {
51 if (entry.second.size() > 1) {
59 if (value_to_literals.size() == vars.size()) {
60 for (
const auto& entry : value_to_literals) {
68 const std::vector<AffineExpression>& expressions) {
70 if (expressions.empty())
return;
74 model->TakeOwnership(constraint);
79 const std::vector<IntegerVariable>& vars) {
81 if (vars.empty())
return;
82 std::vector<AffineExpression> expressions;
83 expressions.reserve(vars.size());
84 for (
const IntegerVariable
var : vars) {
90 model->TakeOwnership(constraint);
95 const std::vector<IntegerVariable>& variables) {
97 if (variables.size() < 3)
return;
103 model->TakeOwnership(constraint);
110 : num_variables_(variables.size()),
111 variables_(std::move(variables)),
113 integer_trail_(integer_trail) {
117 variable_min_value_.resize(num_variables_);
118 variable_max_value_.resize(num_variables_);
119 variable_literal_index_.resize(num_variables_);
120 int num_fixed_variables = 0;
121 for (
int x = 0; x < num_variables_; x++) {
122 variable_min_value_[x] = integer_trail_->
LowerBound(variables_[x]).value();
123 variable_max_value_[x] = integer_trail_->
UpperBound(variables_[x]).value();
126 min_value =
std::min(min_value, variable_min_value_[x]);
127 max_value =
std::max(max_value, variable_max_value_[x]);
131 if (variable_min_value_[x] == variable_max_value_[x]) {
132 num_fixed_variables++;
143 int64_t size = variable_max_value_[x] - variable_min_value_[x] + 1;
146 int64_t
value = entry.value.value();
148 if (
value < variable_min_value_[x] || variable_max_value_[x] <
value) {
151 variable_literal_index_[x][
value - variable_min_value_[x]] =
152 entry.literal.Index();
155 min_all_values_ = min_value;
156 num_all_values_ = max_value - min_value + 1;
158 successor_.resize(num_variables_);
159 variable_to_value_.assign(num_variables_, -1);
160 visiting_.resize(num_variables_);
161 variable_visited_from_.resize(num_variables_);
162 residual_graph_successors_.resize(num_variables_ + num_all_values_ + 1);
163 component_number_.resize(num_variables_ + num_all_values_ + 1);
167 const int id = watcher->
Register(
this);
169 for (
const auto& literal_indices : variable_literal_index_) {
170 for (
const LiteralIndex li : literal_indices) {
181 LiteralIndex AllDifferentConstraint::VariableLiteralIndexOf(
int x,
183 return (
value < variable_min_value_[x] || variable_max_value_[x] <
value)
185 : variable_literal_index_[x][
value - variable_min_value_[x]];
188 inline bool AllDifferentConstraint::VariableHasPossibleValue(
int x,
190 LiteralIndex li = VariableLiteralIndexOf(x,
value);
197 bool AllDifferentConstraint::MakeAugmentingPath(
int start) {
202 int num_to_visit = 0;
205 visiting_[num_to_visit++] = start;
206 variable_visited_[start] =
true;
207 variable_visited_from_[start] = -1;
209 while (num_visited < num_to_visit) {
211 const int node = visiting_[num_visited++];
213 for (
const int value : successor_[node]) {
214 if (value_visited_[
value])
continue;
215 value_visited_[
value] =
true;
216 if (value_to_variable_[
value] == -1) {
218 int path_node = node;
219 int path_value =
value;
220 while (path_node != -1) {
221 int old_value = variable_to_value_[path_node];
222 variable_to_value_[path_node] = path_value;
223 value_to_variable_[path_value] = path_node;
224 path_node = variable_visited_from_[path_node];
225 path_value = old_value;
230 const int next_node = value_to_variable_[
value];
231 variable_visited_[next_node] =
true;
232 visiting_[num_to_visit++] = next_node;
233 variable_visited_from_[next_node] = node;
257 prev_matching_ = variable_to_value_;
258 value_to_variable_.assign(num_all_values_, -1);
259 variable_to_value_.assign(num_variables_, -1);
260 for (
int x = 0; x < num_variables_; x++) {
261 successor_[x].clear();
262 const int64_t min_value = integer_trail_->
LowerBound(variables_[x]).value();
263 const int64_t max_value = integer_trail_->
UpperBound(variables_[x]).value();
265 if (VariableHasPossibleValue(x,
value)) {
266 const int offset_value =
value - min_all_values_;
268 successor_[x].push_back(offset_value);
271 if (successor_[x].size() == 1) {
272 const int offset_value = successor_[x][0];
273 if (value_to_variable_[offset_value] == -1) {
274 value_to_variable_[offset_value] = x;
275 variable_to_value_[x] = offset_value;
283 for (
int x = 0; x < num_variables_; x++) {
284 for (
const int offset_value : successor_[x]) {
285 if (value_to_variable_[offset_value] != -1 &&
286 value_to_variable_[offset_value] != x) {
287 LOG(
FATAL) <<
"Should have been propagated by AllDifferentBinary()!";
294 for (
int x = 0; x < num_variables_; x++) {
295 if (variable_to_value_[x] != -1)
continue;
296 const int prev_value = prev_matching_[x];
297 if (prev_value == -1 || value_to_variable_[prev_value] != -1)
continue;
299 if (VariableHasPossibleValue(x, prev_matching_[x] + min_all_values_)) {
300 variable_to_value_[x] = prev_matching_[x];
301 value_to_variable_[prev_matching_[x]] = x;
307 for (; x < num_variables_; x++) {
308 if (variable_to_value_[x] == -1) {
309 value_visited_.assign(num_all_values_,
false);
310 variable_visited_.assign(num_variables_,
false);
311 MakeAugmentingPath(x);
313 if (variable_to_value_[x] == -1)
break;
319 if (x < num_variables_) {
323 for (
int y = 0; y < num_variables_; y++) {
324 if (!variable_visited_[y])
continue;
325 for (
int value = variable_min_value_[y];
value <= variable_max_value_[y];
327 const LiteralIndex li = VariableLiteralIndexOf(y,
value);
328 if (li >= 0 && !value_visited_[
value - min_all_values_]) {
330 conflict->push_back(
Literal(li));
339 for (
int x = 0; x < num_variables_; x++) {
340 residual_graph_successors_[x].clear();
341 for (
const int succ : successor_[x]) {
342 if (succ != variable_to_value_[x]) {
343 residual_graph_successors_[x].push_back(num_variables_ + succ);
347 for (
int offset_value = 0; offset_value < num_all_values_; offset_value++) {
348 residual_graph_successors_[num_variables_ + offset_value].clear();
349 if (value_to_variable_[offset_value] != -1) {
350 residual_graph_successors_[num_variables_ + offset_value].push_back(
351 value_to_variable_[offset_value]);
354 const int dummy_node = num_variables_ + num_all_values_;
355 residual_graph_successors_[dummy_node].clear();
356 if (num_variables_ < num_all_values_) {
357 for (
int x = 0; x < num_variables_; x++) {
358 residual_graph_successors_[dummy_node].push_back(x);
360 for (
int offset_value = 0; offset_value < num_all_values_; offset_value++) {
361 if (value_to_variable_[offset_value] == -1) {
362 residual_graph_successors_[num_variables_ + offset_value].push_back(
370 explicit SccOutput(std::vector<int>* c) : components(c) {}
371 void emplace_back(
int const*
b,
int const* e) {
372 for (
int const* it =
b; it < e; ++it) {
373 (*components)[*it] = num_components;
377 int num_components = 0;
378 std::vector<int>* components;
380 SccOutput scc_output(&component_number_);
382 static_cast<int>(residual_graph_successors_.size()),
383 residual_graph_successors_, &scc_output);
386 for (
int x = 0; x < num_variables_; x++) {
387 if (successor_[x].size() == 1)
continue;
388 for (
const int offset_value : successor_[x]) {
389 const int value_node = offset_value + num_variables_;
390 if (variable_to_value_[x] != offset_value &&
391 component_number_[x] != component_number_[value_node] &&
392 VariableHasPossibleValue(x, offset_value + min_all_values_)) {
397 value_visited_.assign(num_all_values_,
false);
398 variable_visited_.assign(num_variables_,
false);
400 const int old_variable = value_to_variable_[offset_value];
401 variable_to_value_[old_variable] = -1;
402 const int old_value = variable_to_value_[x];
403 value_to_variable_[old_value] = -1;
404 variable_to_value_[x] = offset_value;
405 value_to_variable_[offset_value] = x;
407 value_visited_[offset_value] =
true;
408 MakeAugmentingPath(old_variable);
409 DCHECK_EQ(variable_to_value_[old_variable], -1);
412 for (
int y = 0; y < num_variables_; y++) {
413 if (!variable_visited_[y])
continue;
414 for (
int value = variable_min_value_[y];
416 const LiteralIndex li = VariableLiteralIndexOf(y,
value);
417 if (li >= 0 && !value_visited_[
value - min_all_values_]) {
419 reason->push_back(
Literal(li));
424 const LiteralIndex li =
425 VariableLiteralIndexOf(x, offset_value + min_all_values_);
437 const std::vector<AffineExpression>& expressions,
439 : integer_trail_(integer_trail) {
440 CHECK(!expressions.empty());
443 const int capacity = expressions.size() + 2;
444 index_to_start_index_.resize(
capacity);
445 index_to_end_index_.resize(
capacity);
446 index_is_present_.resize(
capacity,
false);
449 for (
int i = 0; i < expressions.size(); ++i) {
450 bounds_.push_back({expressions[i]});
451 negated_bounds_.push_back({expressions[i].Negated()});
456 if (!PropagateLowerBounds())
return false;
461 const bool result = PropagateLowerBounds();
466 void AllDifferentBoundsPropagator::FillHallReason(IntegerValue hall_lb,
467 IntegerValue hall_ub) {
468 integer_reason_.clear();
469 const int limit = GetIndex(hall_ub);
470 for (
int i = GetIndex(hall_lb); i <= limit; ++i) {
477 int AllDifferentBoundsPropagator::FindStartIndexAndCompressPath(
int index) {
479 int start_index =
index;
481 const int next = index_to_start_index_[start_index];
482 if (start_index ==
next)
break;
488 const int next = index_to_start_index_[
index];
489 if (start_index ==
next)
break;
490 index_to_start_index_[
index] = start_index;
496 bool AllDifferentBoundsPropagator::PropagateLowerBounds() {
498 for (CachedBounds& entry : bounds_) {
499 entry.lb = integer_trail_->
LowerBound(entry.expr);
500 entry.ub = integer_trail_->
UpperBound(entry.expr);
503 [](CachedBounds
a, CachedBounds
b) {
return a.lb <
b.lb; });
508 int num_in_window = 1;
511 IntegerValue min_lb = bounds_.front().lb;
513 const int size = bounds_.size();
514 for (
int i = 1; i < size; ++i) {
515 const IntegerValue lb = bounds_[i].lb;
520 if (lb <= min_lb + IntegerValue(num_in_window - 1)) {
526 if (num_in_window > 1) {
527 absl::Span<CachedBounds> window(&bounds_[start], num_in_window);
528 if (!PropagateLowerBoundsInternal(min_lb, window)) {
540 if (num_in_window > 1) {
541 absl::Span<CachedBounds> window(&bounds_[start], num_in_window);
542 return PropagateLowerBoundsInternal(min_lb, window);
548 bool AllDifferentBoundsPropagator::PropagateLowerBoundsInternal(
549 IntegerValue min_lb, absl::Span<CachedBounds>
bounds) {
550 hall_starts_.clear();
555 base_ = min_lb - IntegerValue(1);
558 for (
const int i : indices_to_clear_) {
559 index_is_present_[i] =
false;
561 indices_to_clear_.clear();
565 [](CachedBounds
a, CachedBounds
b) {
return a.ub <
b.ub; });
566 for (
const CachedBounds entry :
bounds) {
567 const AffineExpression expr = entry.expr;
572 const IntegerValue lb = entry.lb;
573 const int lb_index = GetIndex(lb);
574 const bool value_is_covered = index_is_present_[lb_index];
577 if (value_is_covered) {
578 const int hall_index =
581 if (hall_index < hall_ends_.size() && hall_starts_[hall_index] <= lb) {
582 const IntegerValue hs = hall_starts_[hall_index];
583 const IntegerValue he = hall_ends_[hall_index];
584 FillHallReason(hs, he);
585 integer_reason_.push_back(expr.GreaterOrEqual(hs));
586 if (!integer_trail_->
SafeEnqueue(expr.GreaterOrEqual(he + 1),
598 int new_index = lb_index;
599 int start_index = lb_index;
600 int end_index = lb_index;
601 if (value_is_covered) {
602 start_index = FindStartIndexAndCompressPath(new_index);
603 new_index = index_to_end_index_[start_index] + 1;
604 end_index = new_index;
606 if (index_is_present_[new_index - 1]) {
607 start_index = FindStartIndexAndCompressPath(new_index - 1);
610 if (index_is_present_[new_index + 1]) {
611 end_index = index_to_end_index_[new_index + 1];
612 index_to_start_index_[new_index + 1] = start_index;
616 index_to_end_index_[start_index] = end_index;
620 index_to_start_index_[new_index] = start_index;
621 index_to_expr_[new_index] = expr;
622 index_is_present_[new_index] =
true;
623 indices_to_clear_.push_back(new_index);
632 const IntegerValue end = GetValue(end_index);
633 if (end > integer_trail_->
UpperBound(expr))
return true;
642 if (end == entry.ub) {
643 const IntegerValue start = GetValue(start_index);
644 while (!hall_starts_.empty() && start <= hall_starts_.back()) {
645 hall_starts_.pop_back();
646 hall_ends_.pop_back();
648 DCHECK(hall_ends_.empty() || hall_ends_.back() < start);
649 hall_starts_.push_back(start);
650 hall_ends_.push_back(end);
658 const int id = watcher->
Register(
this);
659 for (
const CachedBounds& entry : bounds_) {
std::function< void(Model *)> AllDifferentBinary(const std::vector< IntegerVariable > &vars)
void IncrementalSort(int max_comparisons, Iterator begin, Iterator end, Compare comp=Compare{}, bool is_stable=false)
IntegerLiteral GreaterOrEqual(IntegerValue bound) const
void RegisterWith(GenericLiteralWatcher *watcher)
AllDifferentBoundsPropagator(const std::vector< AffineExpression > &expressions, IntegerTrail *integer_trail)
Class that owns everything related to a particular optimization model.
bool VariableIsFullyEncoded(IntegerVariable var) const
std::vector< Literal > * MutableConflict()
IntegerValue LowerBound(IntegerVariable i) const
bool LiteralIsFalse(Literal literal) const
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
const LiteralIndex kTrueLiteralIndex(-2)
std::vector< Literal > * GetEmptyVectorToStoreReason(int trail_index) const
void FullyEncodeVariable(IntegerVariable var)
std::function< void(Model *)> AtMostOneConstraint(const std::vector< Literal > &literals)
ABSL_MUST_USE_RESULT bool SafeEnqueue(IntegerLiteral i_lit, absl::Span< const IntegerLiteral > integer_reason)
void WatchAffineExpression(AffineExpression e, int id)
#define DCHECK_NE(val1, val2)
bool VariableIsAssigned(BooleanVariable var) const
std::vector< ValueLiteralPair > FullDomainEncoding(IntegerVariable var) const
void SetPropagatorPriority(int id, int priority)
#define DCHECK_GE(val1, val2)
void WatchLiteral(Literal l, int id, int watch_index=-1)
const LiteralIndex kFalseLiteralIndex(-3)
std::function< void(Model *)> AllDifferentOnBounds(const std::vector< IntegerVariable > &vars)
#define DCHECK(condition)
AllDifferentConstraint(std::vector< IntegerVariable > variables, IntegerEncoder *encoder, Trail *trail, IntegerTrail *integer_trail)
void FindStronglyConnectedComponents(const NodeIndex num_nodes, const Graph &graph, SccOutput *components)
std::function< std::vector< ValueLiteralPair >Model *)> FullyEncodeVariable(IntegerVariable var)
#define DCHECK_EQ(val1, val2)
std::function< void(Model *)> AllDifferentAC(const std::vector< IntegerVariable > &variables)
int Register(PropagatorInterface *propagator)
IntegerValue UpperBound(IntegerVariable i) const
SharedBoundsManager * bounds
Collection of objects used to extend the Constraint Solver library.
const IntegerVariable kNoIntegerVariable(-1)
IntegerLiteral LowerOrEqual(IntegerValue bound) const
const VariablesAssignment & Assignment() const
void RegisterWith(GenericLiteralWatcher *watcher)
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
ABSL_MUST_USE_RESULT bool EnqueueWithStoredReason(Literal true_literal)
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)