21#include "absl/algorithm/container.h"
22#include "absl/container/btree_map.h"
23#include "absl/container/flat_hash_map.h"
24#include "absl/log/check.h"
25#include "absl/types/span.h"
41 absl::Span<const IntegerVariable> vars) {
42 return [=, vars = std::vector<IntegerVariable>(vars.begin(), vars.end())](
48 absl::btree_map<IntegerValue, std::vector<Literal>> value_to_literals;
50 for (
const IntegerVariable var : vars) {
53 value_to_literals[entry.value].push_back(entry.literal);
58 for (
const auto& entry : value_to_literals) {
59 if (entry.second.size() > 1) {
67 if (value_to_literals.size() == vars.size()) {
68 for (
const auto& entry : value_to_literals) {
76 absl::Span<const Literal> enforcement_literals,
77 absl::Span<const AffineExpression> expressions) {
78 return [=, expressions = std::vector<AffineExpression>(
79 expressions.begin(), expressions.end())](
Model* model) {
80 if (expressions.empty())
return;
87 absl::Span<const IntegerVariable> vars) {
88 return [=, vars = std::vector<IntegerVariable>(vars.begin(), vars.end())](
90 if (vars.empty())
return;
91 std::vector<AffineExpression> expressions;
92 expressions.reserve(vars.size());
93 for (
const IntegerVariable var : vars) {
97 {}, expressions, model));
102 absl::Span<const IntegerVariable> variables) {
103 return [variables](
Model* model) {
104 if (variables.size() < 3)
return;
109 model->TakeOwnership(constraint);
114 absl::Span<const IntegerVariable> variables,
Model* model)
115 : num_variables_(variables.size()),
116 trail_(model->GetOrCreate<
Trail>()),
121 absl::flat_hash_map<IntegerValue, int> dense_indexing;
122 variable_to_possible_values_.resize(num_variables_);
124 for (
int x = 0; x < num_variables_; x++) {
125 const IntegerValue lb = integer_trail_->LowerBound(variables[x]);
126 const IntegerValue ub = integer_trail_->UpperBound(variables[x]);
131 const auto [it, inserted] = dense_indexing.insert({lb, num_values_});
132 if (inserted) ++num_values_;
134 variable_to_possible_values_[x].push_back(
135 {it->second, encoder->GetTrueLiteral()});
140 if (!encoder->VariableIsFullyEncoded(variables[x])) {
141 encoder->FullyEncodeVariable(variables[x]);
145 for (
const auto [value, lit] : encoder->FullDomainEncoding(variables[x])) {
146 const auto [it, inserted] = dense_indexing.insert({value, num_values_});
147 if (inserted) ++num_values_;
149 variable_to_possible_values_[x].push_back({it->second, lit});
154 variable_to_possible_values_[x],
155 [](
const std::pair<int, Literal>& a,
const std::pair<int, Literal>&
b) {
156 return a.first <
b.first;
160 variable_to_value_.assign(num_variables_, -1);
161 visiting_.resize(num_variables_);
162 variable_visited_from_.resize(num_variables_);
163 component_number_.resize(num_variables_ + num_values_ + 1);
167 int num_nodes, absl::Span<const int> tails, absl::Span<const int> heads,
168 absl::Span<const Literal> literals,
Model* model)
169 : num_variables_(num_nodes),
170 trail_(model->GetOrCreate<
Trail>()),
172 num_values_ = num_nodes;
175 const int num_arcs = tails.size();
176 variable_to_possible_values_.resize(num_variables_);
177 for (
int a = 0; a < num_arcs; ++a) {
178 variable_to_possible_values_[tails[a]].push_back({heads[a], literals[a]});
181 variable_to_value_.assign(num_variables_, -1);
182 visiting_.resize(num_variables_);
183 variable_visited_from_.resize(num_variables_);
184 component_number_.resize(num_variables_ + num_values_ + 1);
188 const int id = watcher->
Register(
this);
190 for (
int x = 0; x < num_variables_; x++) {
191 for (
const auto [_, lit] : variable_to_possible_values_[x]) {
193 if (!trail_->Assignment().LiteralIsAssigned(lit)) {
201bool AllDifferentConstraint::MakeAugmentingPath(
int start) {
206 int num_to_visit = 0;
209 visiting_[num_to_visit++] = start;
210 variable_visited_[start] =
true;
211 variable_visited_from_[start] = -1;
213 while (num_visited < num_to_visit) {
215 const int node = visiting_[num_visited++];
217 for (
const int value : successor_[node]) {
218 if (value_visited_[value])
continue;
219 value_visited_[value] =
true;
220 if (value_to_variable_[value] == -1) {
222 int path_node = node;
223 int path_value = value;
224 while (path_node != -1) {
225 int old_value = variable_to_value_[path_node];
226 variable_to_value_[path_node] = path_value;
227 value_to_variable_[path_value] = path_node;
228 path_node = variable_visited_from_[path_node];
229 path_value = old_value;
234 const int next_node = value_to_variable_[value];
235 variable_visited_[next_node] =
true;
236 visiting_[num_to_visit++] = next_node;
237 variable_visited_from_[next_node] = node;
261 prev_matching_ = variable_to_value_;
262 value_to_variable_.assign(num_values_, -1);
263 variable_to_value_.assign(num_variables_, -1);
266 for (
int x = 0; x < num_variables_; x++) {
268 for (
const auto [value, lit] : variable_to_possible_values_[x]) {
269 if (assignment.LiteralIsFalse(lit))
continue;
272 successor_.AppendToLastVector(value);
275 if (prev_matching_[x] == value && value_to_variable_[value] == -1) {
276 variable_to_value_[x] = prev_matching_[x];
277 value_to_variable_[prev_matching_[x]] = x;
280 if (successor_[x].size() == 1) {
281 const int value = successor_[x][0];
282 if (value_to_variable_[value] == -1) {
283 value_to_variable_[value] = x;
284 variable_to_value_[x] = value;
291 for (; x < num_variables_; x++) {
292 if (variable_to_value_[x] == -1) {
293 value_visited_.assign(num_values_,
false);
294 variable_visited_.assign(num_variables_,
false);
295 MakeAugmentingPath(x);
297 if (variable_to_value_[x] == -1)
break;
303 if (x < num_variables_) {
305 std::vector<Literal>* conflict = trail_->MutableConflict();
307 for (
int y = 0; y < num_variables_; y++) {
308 if (!variable_visited_[y])
continue;
309 for (
const auto [value, lit] : variable_to_possible_values_[y]) {
310 if (!value_visited_[value]) {
311 DCHECK(assignment.LiteralIsFalse(lit));
312 conflict->push_back(lit);
321 residual_graph_successors_.clear();
322 for (
int x = 0; x < num_variables_; x++) {
323 residual_graph_successors_.Add({});
324 for (
const int succ : successor_[x]) {
325 if (succ != variable_to_value_[x]) {
326 residual_graph_successors_.AppendToLastVector(num_variables_ + succ);
331 const int dummy_node = num_variables_ + num_values_;
332 const bool need_dummy = num_variables_ < num_values_;
333 for (
int value = 0; value < num_values_; value++) {
334 residual_graph_successors_.Add({});
335 if (value_to_variable_[value] != -1) {
336 residual_graph_successors_.AppendToLastVector(value_to_variable_[value]);
337 }
else if (need_dummy) {
338 residual_graph_successors_.AppendToLastVector(dummy_node);
342 DCHECK_EQ(residual_graph_successors_.size(), dummy_node);
343 residual_graph_successors_.Add({});
344 for (
int x = 0; x < num_variables_; x++) {
345 residual_graph_successors_.AppendToLastVector(x);
351 explicit SccOutput(std::vector<int>* c) : components(c) {}
352 void emplace_back(
int const*
b,
int const* e) {
353 for (
int const* it =
b; it < e; ++it) {
354 (*components)[*it] = num_components;
358 int num_components = 0;
359 std::vector<int>* components;
361 SccOutput scc_output(&component_number_);
363 static_cast<int>(residual_graph_successors_.size()),
364 residual_graph_successors_, &scc_output);
367 for (
int x = 0; x < num_variables_; x++) {
368 if (successor_[x].size() == 1)
continue;
369 for (
const auto [value, x_lit] : variable_to_possible_values_[x]) {
370 if (assignment.LiteralIsFalse(x_lit))
continue;
372 const int value_node = value + num_variables_;
373 DCHECK_LT(value_node, component_number_.size());
374 if (variable_to_value_[x] != value &&
375 component_number_[x] != component_number_[value_node]) {
380 value_visited_.assign(num_values_,
false);
381 variable_visited_.assign(num_variables_,
false);
383 const int old_variable = value_to_variable_[value];
384 DCHECK_GE(old_variable, 0);
385 DCHECK_LT(old_variable, num_variables_);
386 variable_to_value_[old_variable] = -1;
387 const int old_value = variable_to_value_[x];
388 value_to_variable_[old_value] = -1;
389 variable_to_value_[x] = value;
390 value_to_variable_[value] = x;
392 value_visited_[value] =
true;
393 MakeAugmentingPath(old_variable);
394 DCHECK_EQ(variable_to_value_[old_variable], -1);
396 std::vector<Literal>* reason = trail_->GetEmptyVectorToStoreReason();
397 for (
int y = 0; y < num_variables_; y++) {
398 if (!variable_visited_[y])
continue;
399 for (
const auto [value, y_lit] : variable_to_possible_values_[y]) {
400 if (!value_visited_[value]) {
401 DCHECK(assignment.LiteralIsFalse(y_lit));
402 reason->push_back(y_lit);
407 return trail_->EnqueueWithStoredReason(
kNoClauseId, x_lit.Negated());
416 absl::Span<const Literal> enforcement_literals,
417 absl::Span<const AffineExpression> expressions,
Model* model)
420 CHECK(!expressions.empty());
423 const int capacity = expressions.size() + 2;
424 index_to_start_index_.resize(capacity);
425 index_to_end_index_.resize(capacity);
426 index_is_present_.Resize(capacity);
429 for (
int i = 0;
i < expressions.size(); ++
i) {
430 bounds_.push_back({expressions[
i]});
431 negated_bounds_.push_back({expressions[
i].Negated()});
435 enforcement_id_ = enforcement_helper_.
Register(enforcement_literals, watcher,
436 RegisterWith(watcher));
445 if (!PropagateLowerBounds())
return false;
449 std::swap(bounds_, negated_bounds_);
450 const bool result = PropagateLowerBounds();
451 std::swap(bounds_, negated_bounds_);
455void AllDifferentBoundsPropagator::FillHallReason(IntegerValue hall_lb,
456 IntegerValue hall_ub) {
457 integer_reason_.clear();
458 const int limit = GetIndex(hall_ub);
459 for (
int i = GetIndex(hall_lb);
i <= limit; ++
i) {
466int AllDifferentBoundsPropagator::FindStartIndexAndCompressPath(
int index) {
468 int start_index = index;
470 const int next = index_to_start_index_[start_index];
471 if (start_index == next)
break;
477 const int next = index_to_start_index_[index];
478 if (start_index == next)
break;
479 index_to_start_index_[index] = start_index;
485bool AllDifferentBoundsPropagator::PropagateLowerBounds() {
487 for (CachedBounds& entry : bounds_) {
488 entry.lb = integer_trail_.LowerBound(entry.expr);
489 entry.ub = integer_trail_.UpperBound(entry.expr);
492 [](CachedBounds a, CachedBounds
b) { return a.lb < b.lb; });
497 int num_in_window = 1;
500 IntegerValue min_lb = bounds_.front().lb;
502 const int size = bounds_.size();
503 for (
int i = 1;
i < size; ++
i) {
504 const IntegerValue lb = bounds_[
i].lb;
509 if (lb <= min_lb + IntegerValue(num_in_window - 1)) {
515 if (num_in_window > 1) {
516 absl::Span<CachedBounds> window(&bounds_[start], num_in_window);
517 if (!PropagateLowerBoundsInternal(min_lb, window)) {
529 if (num_in_window > 1) {
530 absl::Span<CachedBounds> window(&bounds_[start], num_in_window);
531 return PropagateLowerBoundsInternal(min_lb, window);
537bool AllDifferentBoundsPropagator::PropagateLowerBoundsInternal(
538 IntegerValue min_lb, absl::Span<CachedBounds> bounds) {
539 hall_starts_.clear();
544 base_ = min_lb - IntegerValue(1);
546 index_is_present_.ResetAllToFalse();
549 std::sort(bounds.begin(), bounds.end(),
550 [](CachedBounds a, CachedBounds
b) { return a.ub < b.ub; });
551 for (
const CachedBounds entry : bounds) {
552 const AffineExpression expr = entry.expr;
557 const IntegerValue lb = entry.lb;
558 const int lb_index = GetIndex(lb);
559 const bool value_is_covered = index_is_present_[lb_index];
562 if (value_is_covered) {
563 const int hall_index =
564 std::lower_bound(hall_ends_.begin(), hall_ends_.end(), lb) -
566 if (hall_index < hall_ends_.size() && hall_starts_[hall_index] <= lb) {
567 const IntegerValue hs = hall_starts_[hall_index];
568 const IntegerValue he = hall_ends_[hall_index];
569 FillHallReason(hs, he);
570 integer_reason_.push_back(expr.GreaterOrEqual(hs));
571 if (enforcement_helper_.Status(enforcement_id_) ==
573 if (!enforcement_helper_.SafeEnqueue(enforcement_id_,
574 expr.GreaterOrEqual(he + 1),
578 }
else if (he >= entry.ub) {
579 integer_reason_.push_back(expr.LowerOrEqual(entry.ub));
580 return enforcement_helper_.PropagateWhenFalse(
581 enforcement_id_, {}, integer_reason_);
591 int new_index = lb_index;
592 int start_index = lb_index;
593 int end_index = lb_index;
594 if (value_is_covered) {
595 start_index = FindStartIndexAndCompressPath(new_index);
596 new_index = index_to_end_index_[start_index] + 1;
597 end_index = new_index;
599 if (index_is_present_[new_index - 1]) {
600 start_index = FindStartIndexAndCompressPath(new_index - 1);
603 if (index_is_present_[new_index + 1]) {
604 end_index = index_to_end_index_[new_index + 1];
605 index_to_start_index_[new_index + 1] = start_index;
609 index_to_end_index_[start_index] = end_index;
613 index_to_start_index_[new_index] = start_index;
614 index_to_expr_[new_index] = expr;
615 index_is_present_.Set(new_index);
624 const IntegerValue
end = GetValue(end_index);
625 if (
end > integer_trail_.UpperBound(expr))
return true;
634 if (
end == entry.ub) {
635 const IntegerValue start = GetValue(start_index);
636 while (!hall_starts_.empty() && start <= hall_starts_.back()) {
637 hall_starts_.pop_back();
638 hall_ends_.pop_back();
640 DCHECK(hall_ends_.empty() || hall_ends_.back() < start);
641 hall_starts_.push_back(start);
642 hall_ends_.push_back(
end);
649 const int id = watcher->Register(
this);
650 for (
const CachedBounds& entry : bounds_) {
651 watcher->WatchAffineExpression(entry.expr,
id);
653 watcher->NotifyThatPropagatorMayNotReachFixedPointInOnePass(
id);
AllDifferentBoundsPropagator(absl::Span< const Literal > enforcement_literals, absl::Span< const AffineExpression > expressions, Model *model)
AllDifferentConstraint(absl::Span< const IntegerVariable > variables, Model *model)
void RegisterWith(GenericLiteralWatcher *watcher)
void WatchLiteral(Literal l, int id, int watch_index=-1)
void SetPropagatorPriority(int id, int priority)
int Register(PropagatorInterface *propagator)
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)
constexpr ClauseId kNoClauseId(0)
@ CAN_PROPAGATE_ENFORCEMENT
std::function< void(Model *)> AtMostOneConstraint(absl::Span< const Literal > literals)
std::function< void(Model *)> AllDifferentOnBounds(absl::Span< const Literal > enforcement_literals, absl::Span< const AffineExpression > expressions)
std::function< void(Model *)> AllDifferentAC(absl::Span< const IntegerVariable > variables)
ClosedInterval::Iterator end(ClosedInterval interval)
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)
IntegerLiteral GreaterOrEqual(IntegerValue bound) const
IntegerLiteral LowerOrEqual(IntegerValue bound) const