Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
all_different.h
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14#ifndef OR_TOOLS_SAT_ALL_DIFFERENT_H_
15#define OR_TOOLS_SAT_ALL_DIFFERENT_H_
16
17#include <cstdint>
18#include <functional>
19#include <vector>
20
21#include "absl/log/check.h"
22#include "absl/types/span.h"
24#include "ortools/sat/integer.h"
26#include "ortools/sat/model.h"
29
30namespace operations_research {
31namespace sat {
32
33// Enforces that the given tuple of variables takes different values. This fully
34// encodes all the variables and simply enforces a <= 1 constraint on each
35// possible values.
36std::function<void(Model*)> AllDifferentBinary(
37 absl::Span<const IntegerVariable> vars);
38
39// Enforces that the given tuple of variables takes different values.
40// Same as AllDifferentBinary() but use a different propagator that only enforce
41// the so called "bound consistency" on the variable domains.
42//
43// Compared to AllDifferentBinary() this doesn't require fully encoding the
44// variables and it is also quite fast. Note that the propagation is different,
45// this will not remove already taken values from inside a domain, but it will
46// propagates more the domain bounds.
47std::function<void(Model*)> AllDifferentOnBounds(
48 absl::Span<const IntegerVariable> vars);
49std::function<void(Model*)> AllDifferentOnBounds(
50 const std::vector<AffineExpression>& expressions);
51
52// This constraint forces all variables to take different values. This is meant
53// to be used as a complement to an alldifferent decomposition like
54// AllDifferentBinary(): DO NOT USE WITHOUT ONE. Doing the filtering that the
55// decomposition can do with an appropriate algorithm should be cheaper and
56// yield more accurate explanations.
57//
58// It uses the matching algorithm described in Regin at AAAI1994:
59// "A filtering algorithm for constraints of difference in CSPs".
60//
61// This will fully encode variables.
62std::function<void(Model*)> AllDifferentAC(
63 absl::Span<const IntegerVariable> variables);
64
65// Implementation of AllDifferentAC().
67 public:
68 AllDifferentConstraint(absl::Span<const IntegerVariable> variables,
69 Model* model);
70
71 // In a circuit, the successor of all node must be "different".
72 // Thus this propagator can also be used in this context.
73 AllDifferentConstraint(int num_nodes, absl::Span<const int> tails,
74 absl::Span<const int> heads,
75 absl::Span<const Literal> literals, Model* model);
76
77 bool Propagate() final;
79
80 private:
81 // MakeAugmentingPath() is a step in Ford-Fulkerson's augmenting path
82 // algorithm. It changes its current internal state (see vectors below)
83 // to assign a value to the start vertex using an augmenting path.
84 // If it is not possible, it keeps variable_to_value_[start] to -1 and returns
85 // false, otherwise it modifies the current assignment and returns true.
86 // It uses value/variable_visited to mark the nodes it visits during its
87 // search: one can use this information to generate an explanation of failure,
88 // or manipulate it to create what-if scenarios without modifying successor_.
89 bool MakeAugmentingPath(int start);
90
91 // This caches all literals of the fully encoded variables.
92 // Values of a given variable are 0-indexed using offsets variable_min_value_,
93 // the set of all values is globally offset using offset min_all_values_.
94 // TODO(user): compare this encoding to a sparser hash_map encoding.
95 const int num_variables_;
96 const std::vector<IntegerVariable> variables_;
97
98 // Note that we remap all value into [0, num_values_) in a "dense" way.
99 std::vector<std::vector<std::pair<int, Literal>>>
100 variable_to_possible_values_;
101 int64_t num_values_;
102
103 // Internal state of MakeAugmentingPath().
104 // value_to_variable_ and variable_to_value_ represent the current assignment;
105 // -1 means not assigned. Otherwise,
106 // variable_to_value_[var] = value <=> value_to_variable_[value] = var.
107 CompactVectorVector<int> successor_;
108 std::vector<bool> value_visited_;
109 std::vector<bool> variable_visited_;
110 std::vector<int> value_to_variable_;
111 std::vector<int> variable_to_value_;
112 std::vector<int> prev_matching_;
113 std::vector<int> visiting_;
114 std::vector<int> variable_visited_from_;
115
116 // Internal state of ComputeSCCs().
117 // Variable nodes are indexed by [0, num_variables_),
118 // value nodes by [num_variables_, num_variables_ + num_all_values_),
119 // and a dummy node with index num_variables_ + num_all_values_ is added.
120 // The graph passed to ComputeSCCs() is the residual of the possible graph
121 // by the current matching, i.e. its arcs are:
122 // _ (var, val) if val \in dom(var) and var not matched to val,
123 // _ (val, var) if var matched to val,
124 // _ (val, dummy) if val not matched to any variable,
125 // _ (dummy, var) for all variables.
126 // In the original paper, forbidden arcs are identified by detecting that they
127 // are not in any alternating cycle or alternating path starting at a
128 // free vertex. Adding the dummy node allows to factor the alternating path
129 // part in the alternating cycle, and filter with only the SCC decomposition.
130 // When num_variables_ == num_all_values_, the dummy node is useless,
131 // we add it anyway to simplify the code.
132 CompactVectorVector<int> residual_graph_successors_;
133 std::vector<int> component_number_;
134
135 Trail* trail_;
136 IntegerTrail* integer_trail_;
137};
138
139// Implements the all different bound consistent propagator with explanation.
140// That is, given n affine expressions that must take different values, this
141// propagates the bounds of each expression as much as possible. The key is to
142// detect the so called Hall interval which are interval of size k that contains
143// the domain of k expressinos. Because all the variables must take different
144// values, we can deduce that the domain of the other variables cannot contains
145// such Hall interval.
146//
147// We use a "fast" O(n log n) algorithm.
148//
149// TODO(user): It might be difficult to find something faster than what is
150// implemented here. Some related reference:
151// https://cs.uwaterloo.ca/~vanbeek/Publications/ijcai03_TR.pdf
153 public:
154 AllDifferentBoundsPropagator(absl::Span<const AffineExpression> expressions,
155 IntegerTrail* integer_trail);
156
157 // This type is neither copyable nor movable.
160 delete;
161
162 bool Propagate() final;
163 void RegisterWith(GenericLiteralWatcher* watcher);
164
165 private:
166 // We locally cache the lb/ub for faster sorting and to guarantee some
167 // invariant when we push bounds.
168 struct CachedBounds {
169 AffineExpression expr;
170 IntegerValue lb;
171 IntegerValue ub;
172 };
173
174 // Fills integer_reason_ with the reason why we have the given hall interval.
175 void FillHallReason(IntegerValue hall_lb, IntegerValue hall_ub);
176
177 // Do half the job of Propagate(). This will split the variable into
178 // independent subset, and call PropagateLowerBoundsInternal() on each of
179 // them.
180 bool PropagateLowerBounds();
181 bool PropagateLowerBoundsInternal(IntegerValue min_lb,
182 absl::Span<CachedBounds> bounds);
183
184 // Internally, we will maintain a set of non-consecutive integer intervals of
185 // the form [start, end]. Each point (i.e. IntegerValue) of such interval will
186 // be associated to an unique input expression and via an union-find algorithm
187 // point to its start. The end only make sense for representative.
188 //
189 // TODO(user): Because we don't use rank, we have a worst case complexity of
190 // O(n log n). We could try a normal Union-find data structure, but then we
191 // also have to maintain a start vector.
192 //
193 // Note that during the execution of the algorithm we start from empty
194 // intervals and finish with a set of points of size num_vars.
195 //
196 // The list of all points are maintained in the dense vectors index_to_*_
197 // where we have remapped values to indices (with GetIndex()) to make sure it
198 // always fall into the correct range.
199 int FindStartIndexAndCompressPath(int index);
200
201 int GetIndex(IntegerValue value) const {
202 DCHECK_GE(value, base_);
203 DCHECK_LT(value - base_, index_to_start_index_.size());
204 return (value - base_).value();
205 }
206
207 IntegerValue GetValue(int index) const { return base_ + IntegerValue(index); }
208
209 IntegerTrail* integer_trail_;
210
211 // These vector will be either sorted by lb or by -ub.
212 std::vector<CachedBounds> bounds_;
213 std::vector<CachedBounds> negated_bounds_;
214
215 // The list of Hall intervalls detected so far, sorted.
216 std::vector<IntegerValue> hall_starts_;
217 std::vector<IntegerValue> hall_ends_;
218
219 // Non-consecutive intervals related data-structures.
220 IntegerValue base_;
221 std::vector<int> indices_to_clear_;
222 std::vector<int> index_to_start_index_;
223 std::vector<int> index_to_end_index_;
224 std::vector<bool> index_is_present_;
225 std::vector<AffineExpression> index_to_expr_;
226
227 // Temporary integer reason.
228 std::vector<IntegerLiteral> integer_reason_;
229};
230
231} // namespace sat
232} // namespace operations_research
233
234#endif // OR_TOOLS_SAT_ALL_DIFFERENT_H_
void RegisterWith(GenericLiteralWatcher *watcher)
AllDifferentBoundsPropagator(const AllDifferentBoundsPropagator &)=delete
This type is neither copyable nor movable.
AllDifferentBoundsPropagator(absl::Span< const AffineExpression > expressions, IntegerTrail *integer_trail)
AllDifferentBoundsPropagator & operator=(const AllDifferentBoundsPropagator &)=delete
AllDifferentConstraint(absl::Span< const IntegerVariable > variables, Model *model)
void RegisterWith(GenericLiteralWatcher *watcher)
std::function< void(Model *)> AllDifferentBinary(absl::Span< const IntegerVariable > vars)
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.