23#include "absl/algorithm/container.h"
24#include "absl/container/btree_map.h"
25#include "absl/container/flat_hash_map.h"
26#include "absl/log/check.h"
27#include "absl/types/span.h"
42 absl::Span<const IntegerVariable> vars) {
43 return [=, vars = std::vector<IntegerVariable>(vars.begin(), vars.end())](
49 absl::btree_map<IntegerValue, std::vector<Literal>> value_to_literals;
51 for (
const IntegerVariable var : vars) {
54 value_to_literals[entry.value].push_back(entry.literal);
59 for (
const auto& entry : value_to_literals) {
60 if (entry.second.size() > 1) {
68 if (value_to_literals.size() == vars.size()) {
69 for (
const auto& entry : value_to_literals) {
77 const std::vector<AffineExpression>& expressions) {
78 return [=](
Model* model) {
79 if (expressions.empty())
return;
83 model->TakeOwnership(constraint);
88 absl::Span<const IntegerVariable> vars) {
89 return [=, vars = std::vector<IntegerVariable>(vars.begin(), vars.end())](
91 if (vars.empty())
return;
92 std::vector<AffineExpression> expressions;
93 expressions.reserve(vars.size());
94 for (
const IntegerVariable var : vars) {
100 model->TakeOwnership(constraint);
105 absl::Span<const IntegerVariable> variables) {
106 return [variables](
Model* model) {
107 if (variables.size() < 3)
return;
112 model->TakeOwnership(constraint);
117 absl::Span<const IntegerVariable> variables,
Model* model)
118 : num_variables_(variables.size()),
119 trail_(model->GetOrCreate<
Trail>()),
124 absl::flat_hash_map<IntegerValue, int> dense_indexing;
125 variable_to_possible_values_.resize(num_variables_);
127 for (
int x = 0; x < num_variables_; x++) {
128 const IntegerValue lb = integer_trail_->LowerBound(variables[x]);
129 const IntegerValue ub = integer_trail_->UpperBound(variables[x]);
134 const auto [it, inserted] = dense_indexing.insert({lb, num_values_});
135 if (inserted) ++num_values_;
137 variable_to_possible_values_[x].push_back(
138 {it->second, encoder->GetTrueLiteral()});
143 if (!encoder->VariableIsFullyEncoded(variables[x])) {
144 encoder->FullyEncodeVariable(variables[x]);
148 for (
const auto [value, lit] : encoder->FullDomainEncoding(variables[x])) {
149 const auto [it, inserted] = dense_indexing.insert({value, num_values_});
150 if (inserted) ++num_values_;
152 variable_to_possible_values_[x].push_back({it->second, lit});
157 variable_to_possible_values_[x],
158 [](
const std::pair<int, Literal>& a,
const std::pair<int, Literal>&
b) {
159 return a.first <
b.first;
163 variable_to_value_.assign(num_variables_, -1);
164 visiting_.resize(num_variables_);
165 variable_visited_from_.resize(num_variables_);
166 component_number_.resize(num_variables_ + num_values_ + 1);
170 int num_nodes, absl::Span<const int> tails, absl::Span<const int> heads,
171 absl::Span<const Literal> literals,
Model* model)
172 : num_variables_(num_nodes),
173 trail_(model->GetOrCreate<
Trail>()),
175 num_values_ = num_nodes;
178 const int num_arcs = tails.size();
179 variable_to_possible_values_.resize(num_variables_);
180 for (
int a = 0; a < num_arcs; ++a) {
181 variable_to_possible_values_[tails[a]].push_back({heads[a], literals[a]});
184 variable_to_value_.assign(num_variables_, -1);
185 visiting_.resize(num_variables_);
186 variable_visited_from_.resize(num_variables_);
187 component_number_.resize(num_variables_ + num_values_ + 1);
191 const int id = watcher->
Register(
this);
193 for (
int x = 0; x < num_variables_; x++) {
194 for (
const auto [_, lit] : variable_to_possible_values_[x]) {
196 if (!trail_->Assignment().LiteralIsAssigned(lit)) {
204bool AllDifferentConstraint::MakeAugmentingPath(
int start) {
209 int num_to_visit = 0;
212 visiting_[num_to_visit++] = start;
213 variable_visited_[start] =
true;
214 variable_visited_from_[start] = -1;
216 while (num_visited < num_to_visit) {
218 const int node = visiting_[num_visited++];
220 for (
const int value : successor_[node]) {
221 if (value_visited_[value])
continue;
222 value_visited_[value] =
true;
223 if (value_to_variable_[value] == -1) {
225 int path_node = node;
226 int path_value = value;
227 while (path_node != -1) {
228 int old_value = variable_to_value_[path_node];
229 variable_to_value_[path_node] = path_value;
230 value_to_variable_[path_value] = path_node;
231 path_node = variable_visited_from_[path_node];
232 path_value = old_value;
237 const int next_node = value_to_variable_[value];
238 variable_visited_[next_node] =
true;
239 visiting_[num_to_visit++] = next_node;
240 variable_visited_from_[next_node] = node;
264 prev_matching_ = variable_to_value_;
265 value_to_variable_.assign(num_values_, -1);
266 variable_to_value_.assign(num_variables_, -1);
269 for (
int x = 0; x < num_variables_; x++) {
271 for (
const auto [value, lit] : variable_to_possible_values_[x]) {
272 if (assignment.LiteralIsFalse(lit))
continue;
275 successor_.AppendToLastVector(value);
278 if (prev_matching_[x] == value && value_to_variable_[value] == -1) {
279 variable_to_value_[x] = prev_matching_[x];
280 value_to_variable_[prev_matching_[x]] = x;
283 if (successor_[x].size() == 1) {
284 const int value = successor_[x][0];
285 if (value_to_variable_[value] == -1) {
286 value_to_variable_[value] = x;
287 variable_to_value_[x] = value;
294 for (; x < num_variables_; x++) {
295 if (variable_to_value_[x] == -1) {
296 value_visited_.assign(num_values_,
false);
297 variable_visited_.assign(num_variables_,
false);
298 MakeAugmentingPath(x);
300 if (variable_to_value_[x] == -1)
break;
306 if (x < num_variables_) {
308 std::vector<Literal>* conflict = trail_->MutableConflict();
310 for (
int y = 0; y < num_variables_; y++) {
311 if (!variable_visited_[y])
continue;
312 for (
const auto [value, lit] : variable_to_possible_values_[y]) {
313 if (!value_visited_[value]) {
314 DCHECK(assignment.LiteralIsFalse(lit));
315 conflict->push_back(lit);
324 residual_graph_successors_.clear();
325 for (
int x = 0; x < num_variables_; x++) {
326 residual_graph_successors_.Add({});
327 for (
const int succ : successor_[x]) {
328 if (succ != variable_to_value_[x]) {
329 residual_graph_successors_.AppendToLastVector(num_variables_ + succ);
334 const int dummy_node = num_variables_ + num_values_;
335 const bool need_dummy = num_variables_ < num_values_;
336 for (
int value = 0; value < num_values_; value++) {
337 residual_graph_successors_.Add({});
338 if (value_to_variable_[value] != -1) {
339 residual_graph_successors_.AppendToLastVector(value_to_variable_[value]);
340 }
else if (need_dummy) {
341 residual_graph_successors_.AppendToLastVector(dummy_node);
345 DCHECK_EQ(residual_graph_successors_.size(), dummy_node);
346 residual_graph_successors_.Add({});
347 for (
int x = 0; x < num_variables_; x++) {
348 residual_graph_successors_.AppendToLastVector(x);
354 explicit SccOutput(std::vector<int>* c) : components(c) {}
355 void emplace_back(
int const*
b,
int const* e) {
356 for (
int const* it =
b; it < e; ++it) {
357 (*components)[*it] = num_components;
361 int num_components = 0;
362 std::vector<int>* components;
364 SccOutput scc_output(&component_number_);
366 static_cast<int>(residual_graph_successors_.size()),
367 residual_graph_successors_, &scc_output);
370 for (
int x = 0; x < num_variables_; x++) {
371 if (successor_[x].size() == 1)
continue;
372 for (
const auto [value, x_lit] : variable_to_possible_values_[x]) {
373 if (assignment.LiteralIsFalse(x_lit))
continue;
375 const int value_node = value + num_variables_;
376 DCHECK_LT(value_node, component_number_.size());
377 if (variable_to_value_[x] != value &&
378 component_number_[x] != component_number_[value_node]) {
383 value_visited_.assign(num_values_,
false);
384 variable_visited_.assign(num_variables_,
false);
386 const int old_variable = value_to_variable_[value];
387 DCHECK_GE(old_variable, 0);
388 DCHECK_LT(old_variable, num_variables_);
389 variable_to_value_[old_variable] = -1;
390 const int old_value = variable_to_value_[x];
391 value_to_variable_[old_value] = -1;
392 variable_to_value_[x] = value;
393 value_to_variable_[value] = x;
395 value_visited_[value] =
true;
396 MakeAugmentingPath(old_variable);
397 DCHECK_EQ(variable_to_value_[old_variable], -1);
399 std::vector<Literal>* reason = trail_->GetEmptyVectorToStoreReason();
400 for (
int y = 0; y < num_variables_; y++) {
401 if (!variable_visited_[y])
continue;
402 for (
const auto [value, y_lit] : variable_to_possible_values_[y]) {
403 if (!value_visited_[value]) {
404 DCHECK(assignment.LiteralIsFalse(y_lit));
405 reason->push_back(y_lit);
410 return trail_->EnqueueWithStoredReason(x_lit.Negated());
419 absl::Span<const AffineExpression> expressions,
IntegerTrail* integer_trail)
420 : integer_trail_(integer_trail) {
421 CHECK(!expressions.empty());
424 const int capacity = expressions.size() + 2;
425 index_to_start_index_.resize(capacity);
426 index_to_end_index_.resize(capacity);
427 index_is_present_.resize(capacity,
false);
430 for (
int i = 0;
i < expressions.size(); ++
i) {
431 bounds_.push_back({expressions[
i]});
432 negated_bounds_.push_back({expressions[
i].Negated()});
437 if (!PropagateLowerBounds())
return false;
441 std::swap(bounds_, negated_bounds_);
442 const bool result = PropagateLowerBounds();
443 std::swap(bounds_, negated_bounds_);
447void AllDifferentBoundsPropagator::FillHallReason(IntegerValue hall_lb,
448 IntegerValue hall_ub) {
449 integer_reason_.clear();
450 const int limit = GetIndex(hall_ub);
451 for (
int i = GetIndex(hall_lb);
i <= limit; ++
i) {
458int AllDifferentBoundsPropagator::FindStartIndexAndCompressPath(
int index) {
460 int start_index = index;
462 const int next = index_to_start_index_[start_index];
463 if (start_index == next)
break;
469 const int next = index_to_start_index_[index];
470 if (start_index == next)
break;
471 index_to_start_index_[index] = start_index;
477bool AllDifferentBoundsPropagator::PropagateLowerBounds() {
479 for (CachedBounds& entry : bounds_) {
480 entry.lb = integer_trail_->LowerBound(entry.expr);
481 entry.ub = integer_trail_->UpperBound(entry.expr);
484 [](CachedBounds a, CachedBounds
b) { return a.lb < b.lb; });
489 int num_in_window = 1;
492 IntegerValue min_lb = bounds_.front().lb;
494 const int size = bounds_.size();
495 for (
int i = 1;
i < size; ++
i) {
496 const IntegerValue lb = bounds_[
i].lb;
501 if (lb <= min_lb + IntegerValue(num_in_window - 1)) {
507 if (num_in_window > 1) {
508 absl::Span<CachedBounds> window(&bounds_[start], num_in_window);
509 if (!PropagateLowerBoundsInternal(min_lb, window)) {
521 if (num_in_window > 1) {
522 absl::Span<CachedBounds> window(&bounds_[start], num_in_window);
523 return PropagateLowerBoundsInternal(min_lb, window);
529bool AllDifferentBoundsPropagator::PropagateLowerBoundsInternal(
530 IntegerValue min_lb, absl::Span<CachedBounds> bounds) {
531 hall_starts_.clear();
536 base_ = min_lb - IntegerValue(1);
539 for (
const int i : indices_to_clear_) {
540 index_is_present_[
i] =
false;
542 indices_to_clear_.clear();
545 std::sort(bounds.begin(), bounds.end(),
546 [](CachedBounds a, CachedBounds
b) { return a.ub < b.ub; });
547 for (
const CachedBounds entry : bounds) {
548 const AffineExpression expr = entry.expr;
553 const IntegerValue lb = entry.lb;
554 const int lb_index = GetIndex(lb);
555 const bool value_is_covered = index_is_present_[lb_index];
558 if (value_is_covered) {
559 const int hall_index =
560 std::lower_bound(hall_ends_.begin(), hall_ends_.end(), lb) -
562 if (hall_index < hall_ends_.size() && hall_starts_[hall_index] <= lb) {
563 const IntegerValue hs = hall_starts_[hall_index];
564 const IntegerValue he = hall_ends_[hall_index];
565 FillHallReason(hs, he);
566 integer_reason_.push_back(expr.GreaterOrEqual(hs));
567 if (!integer_trail_->SafeEnqueue(expr.GreaterOrEqual(he + 1),
579 int new_index = lb_index;
580 int start_index = lb_index;
581 int end_index = lb_index;
582 if (value_is_covered) {
583 start_index = FindStartIndexAndCompressPath(new_index);
584 new_index = index_to_end_index_[start_index] + 1;
585 end_index = new_index;
587 if (index_is_present_[new_index - 1]) {
588 start_index = FindStartIndexAndCompressPath(new_index - 1);
591 if (index_is_present_[new_index + 1]) {
592 end_index = index_to_end_index_[new_index + 1];
593 index_to_start_index_[new_index + 1] = start_index;
597 index_to_end_index_[start_index] = end_index;
601 index_to_start_index_[new_index] = start_index;
602 index_to_expr_[new_index] = expr;
603 index_is_present_[new_index] =
true;
604 indices_to_clear_.push_back(new_index);
613 const IntegerValue end = GetValue(end_index);
614 if (end > integer_trail_->UpperBound(expr))
return true;
623 if (end == entry.ub) {
624 const IntegerValue start = GetValue(start_index);
625 while (!hall_starts_.empty() && start <= hall_starts_.back()) {
626 hall_starts_.pop_back();
627 hall_ends_.pop_back();
629 DCHECK(hall_ends_.empty() || hall_ends_.back() < start);
630 hall_starts_.push_back(start);
631 hall_ends_.push_back(end);
639 const int id = watcher->
Register(
this);
640 for (
const CachedBounds& entry : bounds_) {
void RegisterWith(GenericLiteralWatcher *watcher)
AllDifferentBoundsPropagator(absl::Span< const AffineExpression > expressions, IntegerTrail *integer_trail)
Implementation of AllDifferentAC().
AllDifferentConstraint(absl::Span< const IntegerVariable > variables, Model *model)
void RegisterWith(GenericLiteralWatcher *watcher)
void WatchAffineExpression(AffineExpression e, int id)
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)
void WatchLiteral(Literal l, int id, int watch_index=-1)
void SetPropagatorPriority(int id, int priority)
int Register(PropagatorInterface *propagator)
Registers a propagator and returns its unique ids.
const std::vector< ValueLiteralPair > & FullDomainEncoding(IntegerVariable var) const
std::function< std::vector< ValueLiteralPair >(Model *)> FullyEncodeVariable(IntegerVariable var)
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
const IntegerVariable kNoIntegerVariable(-1)
std::function< void(Model *)> AllDifferentBinary(absl::Span< const IntegerVariable > vars)
std::function< void(Model *)> AtMostOneConstraint(absl::Span< const Literal > literals)
std::function< void(Model *)> AllDifferentAC(absl::Span< const IntegerVariable > variables)
std::function< void(Model *)> AllDifferentOnBounds(const std::vector< AffineExpression > &expressions)
In SWIG mode, we don't want anything besides these top-level includes.
void IncrementalSort(int max_comparisons, Iterator begin, Iterator end, Compare comp=Compare{}, bool is_stable=false)
void FindStronglyConnectedComponents(NodeIndex num_nodes, const Graph &graph, SccOutput *components)
Simple wrapper function for most usage.
IntegerLiteral GreaterOrEqual(IntegerValue bound) const
var * coeff + constant >= bound.
IntegerLiteral LowerOrEqual(IntegerValue bound) const
var * coeff + constant <= bound.