-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
element.cc
1775 lines (1582 loc) · 61 KB
/
element.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cstdint>
#include <functional>
#include <limits>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "ortools/base/logging.h"
#include "ortools/base/types.h"
#include "ortools/constraint_solver/constraint_solver.h"
#include "ortools/constraint_solver/constraint_solveri.h"
#include "ortools/util/range_minimum_query.h"
#include "ortools/util/string_array.h"
ABSL_FLAG(bool, cp_disable_element_cache, true,
"If true, caching for IntElement is disabled.");
namespace operations_research {
// ----- IntExprElement -----
void LinkVarExpr(Solver* s, IntExpr* expr, IntVar* var);
namespace {
template <class T>
class VectorLess {
public:
explicit VectorLess(const std::vector<T>* values) : values_(values) {}
bool operator()(const T& x, const T& y) const {
return (*values_)[x] < (*values_)[y];
}
private:
const std::vector<T>* values_;
};
template <class T>
class VectorGreater {
public:
explicit VectorGreater(const std::vector<T>* values) : values_(values) {}
bool operator()(const T& x, const T& y) const {
return (*values_)[x] > (*values_)[y];
}
private:
const std::vector<T>* values_;
};
// ----- BaseIntExprElement -----
class BaseIntExprElement : public BaseIntExpr {
public:
BaseIntExprElement(Solver* s, IntVar* e);
~BaseIntExprElement() override {}
int64_t Min() const override;
int64_t Max() const override;
void Range(int64_t* mi, int64_t* ma) override;
void SetMin(int64_t m) override;
void SetMax(int64_t m) override;
void SetRange(int64_t mi, int64_t ma) override;
bool Bound() const override { return (expr_->Bound()); }
// TODO(user) : improve me, the previous test is not always true
void WhenRange(Demon* d) override { expr_->WhenRange(d); }
protected:
virtual int64_t ElementValue(int index) const = 0;
virtual int64_t ExprMin() const = 0;
virtual int64_t ExprMax() const = 0;
IntVar* const expr_;
private:
void UpdateSupports() const;
template <typename T>
void UpdateElementIndexBounds(T check_value) {
const int64_t emin = ExprMin();
const int64_t emax = ExprMax();
int64_t nmin = emin;
int64_t value = ElementValue(nmin);
while (nmin < emax && check_value(value)) {
nmin++;
value = ElementValue(nmin);
}
if (nmin == emax && check_value(value)) {
solver()->Fail();
}
int64_t nmax = emax;
value = ElementValue(nmax);
while (nmax >= nmin && check_value(value)) {
nmax--;
value = ElementValue(nmax);
}
expr_->SetRange(nmin, nmax);
}
mutable int64_t min_;
mutable int min_support_;
mutable int64_t max_;
mutable int max_support_;
mutable bool initial_update_;
IntVarIterator* const expr_iterator_;
};
BaseIntExprElement::BaseIntExprElement(Solver* const s, IntVar* const e)
: BaseIntExpr(s),
expr_(e),
min_(0),
min_support_(-1),
max_(0),
max_support_(-1),
initial_update_(true),
expr_iterator_(expr_->MakeDomainIterator(true)) {
CHECK(s != nullptr);
CHECK(e != nullptr);
}
int64_t BaseIntExprElement::Min() const {
UpdateSupports();
return min_;
}
int64_t BaseIntExprElement::Max() const {
UpdateSupports();
return max_;
}
void BaseIntExprElement::Range(int64_t* mi, int64_t* ma) {
UpdateSupports();
*mi = min_;
*ma = max_;
}
void BaseIntExprElement::SetMin(int64_t m) {
UpdateElementIndexBounds([m](int64_t value) { return value < m; });
}
void BaseIntExprElement::SetMax(int64_t m) {
UpdateElementIndexBounds([m](int64_t value) { return value > m; });
}
void BaseIntExprElement::SetRange(int64_t mi, int64_t ma) {
if (mi > ma) {
solver()->Fail();
}
UpdateElementIndexBounds(
[mi, ma](int64_t value) { return value < mi || value > ma; });
}
void BaseIntExprElement::UpdateSupports() const {
if (initial_update_ || !expr_->Contains(min_support_) ||
!expr_->Contains(max_support_)) {
const int64_t emin = ExprMin();
const int64_t emax = ExprMax();
int64_t min_value = ElementValue(emax);
int64_t max_value = min_value;
int min_support = emax;
int max_support = emax;
const uint64_t expr_size = expr_->Size();
if (expr_size > 1) {
if (expr_size == emax - emin + 1) {
// Value(emax) already stored in min_value, max_value.
for (int64_t index = emin; index < emax; ++index) {
const int64_t value = ElementValue(index);
if (value > max_value) {
max_value = value;
max_support = index;
} else if (value < min_value) {
min_value = value;
min_support = index;
}
}
} else {
for (const int64_t index : InitAndGetValues(expr_iterator_)) {
if (index >= emin && index <= emax) {
const int64_t value = ElementValue(index);
if (value > max_value) {
max_value = value;
max_support = index;
} else if (value < min_value) {
min_value = value;
min_support = index;
}
}
}
}
}
Solver* s = solver();
s->SaveAndSetValue(&min_, min_value);
s->SaveAndSetValue(&min_support_, min_support);
s->SaveAndSetValue(&max_, max_value);
s->SaveAndSetValue(&max_support_, max_support);
s->SaveAndSetValue(&initial_update_, false);
}
}
// ----- IntElementConstraint -----
// This constraint implements 'elem' == 'values'['index'].
// It scans the bounds of 'elem' to propagate on the domain of 'index'.
// It scans the domain of 'index' to compute the new bounds of 'elem'.
class IntElementConstraint : public CastConstraint {
public:
IntElementConstraint(Solver* const s, const std::vector<int64_t>& values,
IntVar* const index, IntVar* const elem)
: CastConstraint(s, elem),
values_(values),
index_(index),
index_iterator_(index_->MakeDomainIterator(true)) {
CHECK(index != nullptr);
}
void Post() override {
Demon* const d =
solver()->MakeDelayedConstraintInitialPropagateCallback(this);
index_->WhenDomain(d);
target_var_->WhenRange(d);
}
void InitialPropagate() override {
index_->SetRange(0, values_.size() - 1);
const int64_t target_var_min = target_var_->Min();
const int64_t target_var_max = target_var_->Max();
int64_t new_min = target_var_max;
int64_t new_max = target_var_min;
to_remove_.clear();
for (const int64_t index : InitAndGetValues(index_iterator_)) {
const int64_t value = values_[index];
if (value < target_var_min || value > target_var_max) {
to_remove_.push_back(index);
} else {
if (value < new_min) {
new_min = value;
}
if (value > new_max) {
new_max = value;
}
}
}
target_var_->SetRange(new_min, new_max);
if (!to_remove_.empty()) {
index_->RemoveValues(to_remove_);
}
}
std::string DebugString() const override {
return absl::StrFormat("IntElementConstraint(%s, %s, %s)",
absl::StrJoin(values_, ", "), index_->DebugString(),
target_var_->DebugString());
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitConstraint(ModelVisitor::kElementEqual, this);
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument, values_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
index_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kTargetArgument,
target_var_);
visitor->EndVisitConstraint(ModelVisitor::kElementEqual, this);
}
private:
const std::vector<int64_t> values_;
IntVar* const index_;
IntVarIterator* const index_iterator_;
std::vector<int64_t> to_remove_;
};
// ----- IntExprElement
IntVar* BuildDomainIntVar(Solver* solver, std::vector<int64_t>* values);
class IntExprElement : public BaseIntExprElement {
public:
IntExprElement(Solver* const s, const std::vector<int64_t>& vals,
IntVar* const expr)
: BaseIntExprElement(s, expr), values_(vals) {}
~IntExprElement() override {}
std::string name() const override {
const int size = values_.size();
if (size > 10) {
return absl::StrFormat("IntElement(array of size %d, %s)", size,
expr_->name());
} else {
return absl::StrFormat("IntElement(%s, %s)", absl::StrJoin(values_, ", "),
expr_->name());
}
}
std::string DebugString() const override {
const int size = values_.size();
if (size > 10) {
return absl::StrFormat("IntElement(array of size %d, %s)", size,
expr_->DebugString());
} else {
return absl::StrFormat("IntElement(%s, %s)", absl::StrJoin(values_, ", "),
expr_->DebugString());
}
}
IntVar* CastToVar() override {
Solver* const s = solver();
IntVar* const var = s->MakeIntVar(values_);
s->AddCastConstraint(
s->RevAlloc(new IntElementConstraint(s, values_, expr_, var)), var,
this);
return var;
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitIntegerExpression(ModelVisitor::kElement, this);
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument, values_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
expr_);
visitor->EndVisitIntegerExpression(ModelVisitor::kElement, this);
}
protected:
int64_t ElementValue(int index) const override {
DCHECK_LT(index, values_.size());
return values_[index];
}
int64_t ExprMin() const override {
return std::max<int64_t>(0, expr_->Min());
}
int64_t ExprMax() const override {
return values_.empty()
? 0
: std::min<int64_t>(values_.size() - 1, expr_->Max());
}
private:
const std::vector<int64_t> values_;
};
// ----- Range Minimum Query-based Element -----
class RangeMinimumQueryExprElement : public BaseIntExpr {
public:
RangeMinimumQueryExprElement(Solver* solver,
const std::vector<int64_t>& values,
IntVar* index);
~RangeMinimumQueryExprElement() override {}
int64_t Min() const override;
int64_t Max() const override;
void Range(int64_t* mi, int64_t* ma) override;
void SetMin(int64_t m) override;
void SetMax(int64_t m) override;
void SetRange(int64_t mi, int64_t ma) override;
bool Bound() const override { return (index_->Bound()); }
// TODO(user) : improve me, the previous test is not always true
void WhenRange(Demon* d) override { index_->WhenRange(d); }
IntVar* CastToVar() override {
// TODO(user): Should we try to make holes in the domain of index_, as we
// do here, or should we only propagate bounds as we do in
// IncreasingIntExprElement ?
IntVar* const var = solver()->MakeIntVar(min_rmq_.array());
solver()->AddCastConstraint(solver()->RevAlloc(new IntElementConstraint(
solver(), min_rmq_.array(), index_, var)),
var, this);
return var;
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitIntegerExpression(ModelVisitor::kElement, this);
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument,
min_rmq_.array());
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
index_);
visitor->EndVisitIntegerExpression(ModelVisitor::kElement, this);
}
private:
int64_t IndexMin() const { return std::max<int64_t>(0, index_->Min()); }
int64_t IndexMax() const {
return std::min<int64_t>(min_rmq_.array().size() - 1, index_->Max());
}
IntVar* const index_;
const RangeMinimumQuery<int64_t, std::less<int64_t>> min_rmq_;
const RangeMinimumQuery<int64_t, std::greater<int64_t>> max_rmq_;
};
RangeMinimumQueryExprElement::RangeMinimumQueryExprElement(
Solver* solver, const std::vector<int64_t>& values, IntVar* index)
: BaseIntExpr(solver), index_(index), min_rmq_(values), max_rmq_(values) {
CHECK(solver != nullptr);
CHECK(index != nullptr);
}
int64_t RangeMinimumQueryExprElement::Min() const {
return min_rmq_.GetMinimumFromRange(IndexMin(), IndexMax() + 1);
}
int64_t RangeMinimumQueryExprElement::Max() const {
return max_rmq_.GetMinimumFromRange(IndexMin(), IndexMax() + 1);
}
void RangeMinimumQueryExprElement::Range(int64_t* mi, int64_t* ma) {
const int64_t range_min = IndexMin();
const int64_t range_max = IndexMax() + 1;
*mi = min_rmq_.GetMinimumFromRange(range_min, range_max);
*ma = max_rmq_.GetMinimumFromRange(range_min, range_max);
}
#define UPDATE_RMQ_BASE_ELEMENT_INDEX_BOUNDS(test) \
const std::vector<int64_t>& values = min_rmq_.array(); \
int64_t index_min = IndexMin(); \
int64_t index_max = IndexMax(); \
int64_t value = values[index_min]; \
while (index_min < index_max && (test)) { \
index_min++; \
value = values[index_min]; \
} \
if (index_min == index_max && (test)) { \
solver()->Fail(); \
} \
value = values[index_max]; \
while (index_max >= index_min && (test)) { \
index_max--; \
value = values[index_max]; \
} \
index_->SetRange(index_min, index_max);
void RangeMinimumQueryExprElement::SetMin(int64_t m) {
UPDATE_RMQ_BASE_ELEMENT_INDEX_BOUNDS(value < m);
}
void RangeMinimumQueryExprElement::SetMax(int64_t m) {
UPDATE_RMQ_BASE_ELEMENT_INDEX_BOUNDS(value > m);
}
void RangeMinimumQueryExprElement::SetRange(int64_t mi, int64_t ma) {
if (mi > ma) {
solver()->Fail();
}
UPDATE_RMQ_BASE_ELEMENT_INDEX_BOUNDS(value < mi || value > ma);
}
#undef UPDATE_RMQ_BASE_ELEMENT_INDEX_BOUNDS
// ----- Increasing Element -----
class IncreasingIntExprElement : public BaseIntExpr {
public:
IncreasingIntExprElement(Solver* s, const std::vector<int64_t>& values,
IntVar* index);
~IncreasingIntExprElement() override {}
int64_t Min() const override;
void SetMin(int64_t m) override;
int64_t Max() const override;
void SetMax(int64_t m) override;
void SetRange(int64_t mi, int64_t ma) override;
bool Bound() const override { return (index_->Bound()); }
// TODO(user) : improve me, the previous test is not always true
std::string name() const override {
return absl::StrFormat("IntElement(%s, %s)", absl::StrJoin(values_, ", "),
index_->name());
}
std::string DebugString() const override {
return absl::StrFormat("IntElement(%s, %s)", absl::StrJoin(values_, ", "),
index_->DebugString());
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitIntegerExpression(ModelVisitor::kElement, this);
visitor->VisitIntegerArrayArgument(ModelVisitor::kValuesArgument, values_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
index_);
visitor->EndVisitIntegerExpression(ModelVisitor::kElement, this);
}
void WhenRange(Demon* d) override { index_->WhenRange(d); }
IntVar* CastToVar() override {
Solver* const s = solver();
IntVar* const var = s->MakeIntVar(values_);
LinkVarExpr(s, this, var);
return var;
}
private:
const std::vector<int64_t> values_;
IntVar* const index_;
};
IncreasingIntExprElement::IncreasingIntExprElement(
Solver* const s, const std::vector<int64_t>& values, IntVar* const index)
: BaseIntExpr(s), values_(values), index_(index) {
DCHECK(index);
DCHECK(s);
}
int64_t IncreasingIntExprElement::Min() const {
const int64_t expression_min = std::max<int64_t>(0, index_->Min());
return (expression_min < values_.size()
? values_[expression_min]
: std::numeric_limits<int64_t>::max());
}
void IncreasingIntExprElement::SetMin(int64_t m) {
const int64_t index_min = std::max<int64_t>(0, index_->Min());
const int64_t index_max =
std::min<int64_t>(values_.size() - 1, index_->Max());
if (index_min > index_max || m > values_[index_max]) {
solver()->Fail();
}
const std::vector<int64_t>::const_iterator first =
std::lower_bound(values_.begin(), values_.end(), m);
const int64_t new_index_min = first - values_.begin();
index_->SetMin(new_index_min);
}
int64_t IncreasingIntExprElement::Max() const {
const int64_t expression_max =
std::min<int64_t>(values_.size() - 1, index_->Max());
return (expression_max >= 0 ? values_[expression_max]
: std::numeric_limits<int64_t>::max());
}
void IncreasingIntExprElement::SetMax(int64_t m) {
int64_t index_min = std::max<int64_t>(0, index_->Min());
if (m < values_[index_min]) {
solver()->Fail();
}
const std::vector<int64_t>::const_iterator last_after =
std::upper_bound(values_.begin(), values_.end(), m);
const int64_t new_index_max = (last_after - values_.begin()) - 1;
index_->SetRange(0, new_index_max);
}
void IncreasingIntExprElement::SetRange(int64_t mi, int64_t ma) {
if (mi > ma) {
solver()->Fail();
}
const int64_t index_min = std::max<int64_t>(0, index_->Min());
const int64_t index_max =
std::min<int64_t>(values_.size() - 1, index_->Max());
if (mi > ma || ma < values_[index_min] || mi > values_[index_max]) {
solver()->Fail();
}
const std::vector<int64_t>::const_iterator first =
std::lower_bound(values_.begin(), values_.end(), mi);
const int64_t new_index_min = first - values_.begin();
const std::vector<int64_t>::const_iterator last_after =
std::upper_bound(first, values_.end(), ma);
const int64_t new_index_max = (last_after - values_.begin()) - 1;
// Assign.
index_->SetRange(new_index_min, new_index_max);
}
// ----- Solver::MakeElement(int array, int var) -----
IntExpr* BuildElement(Solver* const solver, const std::vector<int64_t>& values,
IntVar* const index) {
// Various checks.
// Is array constant?
if (IsArrayConstant(values, values[0])) {
solver->AddConstraint(solver->MakeBetweenCt(index, 0, values.size() - 1));
return solver->MakeIntConst(values[0]);
}
// Is array built with booleans only?
// TODO(user): We could maintain the index of the first one.
if (IsArrayBoolean(values)) {
std::vector<int64_t> ones;
int first_zero = -1;
for (int i = 0; i < values.size(); ++i) {
if (values[i] == 1) {
ones.push_back(i);
} else {
first_zero = i;
}
}
if (ones.size() == 1) {
DCHECK_EQ(int64_t{1}, values[ones.back()]);
solver->AddConstraint(solver->MakeBetweenCt(index, 0, values.size() - 1));
return solver->MakeIsEqualCstVar(index, ones.back());
} else if (ones.size() == values.size() - 1) {
solver->AddConstraint(solver->MakeBetweenCt(index, 0, values.size() - 1));
return solver->MakeIsDifferentCstVar(index, first_zero);
} else if (ones.size() == ones.back() - ones.front() + 1) { // contiguous.
solver->AddConstraint(solver->MakeBetweenCt(index, 0, values.size() - 1));
IntVar* const b = solver->MakeBoolVar("ContiguousBooleanElementVar");
solver->AddConstraint(
solver->MakeIsBetweenCt(index, ones.front(), ones.back(), b));
return b;
} else {
IntVar* const b = solver->MakeBoolVar("NonContiguousBooleanElementVar");
solver->AddConstraint(solver->MakeBetweenCt(index, 0, values.size() - 1));
solver->AddConstraint(solver->MakeIsMemberCt(index, ones, b));
return b;
}
}
IntExpr* cache = nullptr;
if (!absl::GetFlag(FLAGS_cp_disable_element_cache)) {
cache = solver->Cache()->FindVarConstantArrayExpression(
index, values, ModelCache::VAR_CONSTANT_ARRAY_ELEMENT);
}
if (cache != nullptr) {
return cache;
} else {
IntExpr* result = nullptr;
if (values.size() >= 2 && index->Min() == 0 && index->Max() == 1) {
result = solver->MakeSum(solver->MakeProd(index, values[1] - values[0]),
values[0]);
} else if (values.size() == 2 && index->Contains(0) && index->Contains(1)) {
solver->AddConstraint(solver->MakeBetweenCt(index, 0, 1));
result = solver->MakeSum(solver->MakeProd(index, values[1] - values[0]),
values[0]);
} else if (IsIncreasingContiguous(values)) {
result = solver->MakeSum(index, values[0]);
} else if (IsIncreasing(values)) {
result = solver->RegisterIntExpr(solver->RevAlloc(
new IncreasingIntExprElement(solver, values, index)));
} else {
if (solver->parameters().use_element_rmq()) {
result = solver->RegisterIntExpr(solver->RevAlloc(
new RangeMinimumQueryExprElement(solver, values, index)));
} else {
result = solver->RegisterIntExpr(
solver->RevAlloc(new IntExprElement(solver, values, index)));
}
}
if (!absl::GetFlag(FLAGS_cp_disable_element_cache)) {
solver->Cache()->InsertVarConstantArrayExpression(
result, index, values, ModelCache::VAR_CONSTANT_ARRAY_ELEMENT);
}
return result;
}
}
} // namespace
IntExpr* Solver::MakeElement(const std::vector<int64_t>& values,
IntVar* const index) {
DCHECK(index);
DCHECK_EQ(this, index->solver());
if (index->Bound()) {
return MakeIntConst(values[index->Min()]);
}
return BuildElement(this, values, index);
}
IntExpr* Solver::MakeElement(const std::vector<int>& values,
IntVar* const index) {
DCHECK(index);
DCHECK_EQ(this, index->solver());
if (index->Bound()) {
return MakeIntConst(values[index->Min()]);
}
return BuildElement(this, ToInt64Vector(values), index);
}
// ----- IntExprFunctionElement -----
namespace {
class IntExprFunctionElement : public BaseIntExprElement {
public:
IntExprFunctionElement(Solver* s, Solver::IndexEvaluator1 values, IntVar* e);
~IntExprFunctionElement() override;
std::string name() const override {
return absl::StrFormat("IntFunctionElement(%s)", expr_->name());
}
std::string DebugString() const override {
return absl::StrFormat("IntFunctionElement(%s)", expr_->DebugString());
}
void Accept(ModelVisitor* const visitor) const override {
// Warning: This will expand all values into a vector.
visitor->BeginVisitIntegerExpression(ModelVisitor::kElement, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
expr_);
visitor->VisitInt64ToInt64Extension(values_, expr_->Min(), expr_->Max());
visitor->EndVisitIntegerExpression(ModelVisitor::kElement, this);
}
protected:
int64_t ElementValue(int index) const override { return values_(index); }
int64_t ExprMin() const override { return expr_->Min(); }
int64_t ExprMax() const override { return expr_->Max(); }
private:
Solver::IndexEvaluator1 values_;
};
IntExprFunctionElement::IntExprFunctionElement(Solver* const s,
Solver::IndexEvaluator1 values,
IntVar* const e)
: BaseIntExprElement(s, e), values_(std::move(values)) {
CHECK(values_ != nullptr);
}
IntExprFunctionElement::~IntExprFunctionElement() {}
// ----- Increasing Element -----
class IncreasingIntExprFunctionElement : public BaseIntExpr {
public:
IncreasingIntExprFunctionElement(Solver* const s,
Solver::IndexEvaluator1 values,
IntVar* const index)
: BaseIntExpr(s), values_(std::move(values)), index_(index) {
DCHECK(values_ != nullptr);
DCHECK(index);
DCHECK(s);
}
~IncreasingIntExprFunctionElement() override {}
int64_t Min() const override { return values_(index_->Min()); }
void SetMin(int64_t m) override {
const int64_t index_min = index_->Min();
const int64_t index_max = index_->Max();
if (m > values_(index_max)) {
solver()->Fail();
}
const int64_t new_index_min = FindNewIndexMin(index_min, index_max, m);
index_->SetMin(new_index_min);
}
int64_t Max() const override { return values_(index_->Max()); }
void SetMax(int64_t m) override {
int64_t index_min = index_->Min();
int64_t index_max = index_->Max();
if (m < values_(index_min)) {
solver()->Fail();
}
const int64_t new_index_max = FindNewIndexMax(index_min, index_max, m);
index_->SetMax(new_index_max);
}
void SetRange(int64_t mi, int64_t ma) override {
const int64_t index_min = index_->Min();
const int64_t index_max = index_->Max();
const int64_t value_min = values_(index_min);
const int64_t value_max = values_(index_max);
if (mi > ma || ma < value_min || mi > value_max) {
solver()->Fail();
}
if (mi <= value_min && ma >= value_max) {
// Nothing to do.
return;
}
const int64_t new_index_min = FindNewIndexMin(index_min, index_max, mi);
const int64_t new_index_max = FindNewIndexMax(new_index_min, index_max, ma);
// Assign.
index_->SetRange(new_index_min, new_index_max);
}
std::string name() const override {
return absl::StrFormat("IncreasingIntExprFunctionElement(values, %s)",
index_->name());
}
std::string DebugString() const override {
return absl::StrFormat("IncreasingIntExprFunctionElement(values, %s)",
index_->DebugString());
}
void WhenRange(Demon* d) override { index_->WhenRange(d); }
void Accept(ModelVisitor* const visitor) const override {
// Warning: This will expand all values into a vector.
visitor->BeginVisitIntegerExpression(ModelVisitor::kElement, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
index_);
if (index_->Min() == 0) {
visitor->VisitInt64ToInt64AsArray(values_, ModelVisitor::kValuesArgument,
index_->Max());
} else {
visitor->VisitInt64ToInt64Extension(values_, index_->Min(),
index_->Max());
}
visitor->EndVisitIntegerExpression(ModelVisitor::kElement, this);
}
private:
int64_t FindNewIndexMin(int64_t index_min, int64_t index_max, int64_t m) {
if (m <= values_(index_min)) {
return index_min;
}
DCHECK_LT(values_(index_min), m);
DCHECK_GE(values_(index_max), m);
int64_t index_lower_bound = index_min;
int64_t index_upper_bound = index_max;
while (index_upper_bound - index_lower_bound > 1) {
DCHECK_LT(values_(index_lower_bound), m);
DCHECK_GE(values_(index_upper_bound), m);
const int64_t pivot = (index_lower_bound + index_upper_bound) / 2;
const int64_t pivot_value = values_(pivot);
if (pivot_value < m) {
index_lower_bound = pivot;
} else {
index_upper_bound = pivot;
}
}
DCHECK(values_(index_upper_bound) >= m);
return index_upper_bound;
}
int64_t FindNewIndexMax(int64_t index_min, int64_t index_max, int64_t m) {
if (m >= values_(index_max)) {
return index_max;
}
DCHECK_LE(values_(index_min), m);
DCHECK_GT(values_(index_max), m);
int64_t index_lower_bound = index_min;
int64_t index_upper_bound = index_max;
while (index_upper_bound - index_lower_bound > 1) {
DCHECK_LE(values_(index_lower_bound), m);
DCHECK_GT(values_(index_upper_bound), m);
const int64_t pivot = (index_lower_bound + index_upper_bound) / 2;
const int64_t pivot_value = values_(pivot);
if (pivot_value > m) {
index_upper_bound = pivot;
} else {
index_lower_bound = pivot;
}
}
DCHECK(values_(index_lower_bound) <= m);
return index_lower_bound;
}
Solver::IndexEvaluator1 values_;
IntVar* const index_;
};
} // namespace
IntExpr* Solver::MakeElement(Solver::IndexEvaluator1 values,
IntVar* const index) {
CHECK_EQ(this, index->solver());
return RegisterIntExpr(
RevAlloc(new IntExprFunctionElement(this, std::move(values), index)));
}
IntExpr* Solver::MakeMonotonicElement(Solver::IndexEvaluator1 values,
bool increasing, IntVar* const index) {
CHECK_EQ(this, index->solver());
if (increasing) {
return RegisterIntExpr(
RevAlloc(new IncreasingIntExprFunctionElement(this, values, index)));
} else {
// You need to pass by copy such that opposite_value does not include a
// dandling reference when leaving this scope.
Solver::IndexEvaluator1 opposite_values = [values](int64_t i) {
return -values(i);
};
return RegisterIntExpr(MakeOpposite(RevAlloc(
new IncreasingIntExprFunctionElement(this, opposite_values, index))));
}
}
// ----- IntIntExprFunctionElement -----
namespace {
class IntIntExprFunctionElement : public BaseIntExpr {
public:
IntIntExprFunctionElement(Solver* s, Solver::IndexEvaluator2 values,
IntVar* expr1, IntVar* expr2);
~IntIntExprFunctionElement() override;
std::string DebugString() const override {
return absl::StrFormat("IntIntFunctionElement(%s,%s)",
expr1_->DebugString(), expr2_->DebugString());
}
int64_t Min() const override;
int64_t Max() const override;
void Range(int64_t* lower_bound, int64_t* upper_bound) override;
void SetMin(int64_t lower_bound) override;
void SetMax(int64_t upper_bound) override;
void SetRange(int64_t lower_bound, int64_t upper_bound) override;
bool Bound() const override { return expr1_->Bound() && expr2_->Bound(); }
// TODO(user) : improve me, the previous test is not always true
void WhenRange(Demon* d) override {
expr1_->WhenRange(d);
expr2_->WhenRange(d);
}
void Accept(ModelVisitor* const visitor) const override {
visitor->BeginVisitIntegerExpression(ModelVisitor::kElement, this);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndexArgument,
expr1_);
visitor->VisitIntegerExpressionArgument(ModelVisitor::kIndex2Argument,
expr2_);
// Warning: This will expand all values into a vector.
const int64_t expr1_min = expr1_->Min();
const int64_t expr1_max = expr1_->Max();
visitor->VisitIntegerArgument(ModelVisitor::kMinArgument, expr1_min);
visitor->VisitIntegerArgument(ModelVisitor::kMaxArgument, expr1_max);
for (int i = expr1_min; i <= expr1_max; ++i) {
visitor->VisitInt64ToInt64Extension(
[this, i](int64_t j) { return values_(i, j); }, expr2_->Min(),
expr2_->Max());
}
visitor->EndVisitIntegerExpression(ModelVisitor::kElement, this);
}
private:
int64_t ElementValue(int index1, int index2) const {
return values_(index1, index2);
}
void UpdateSupports() const;
IntVar* const expr1_;
IntVar* const expr2_;
mutable int64_t min_;
mutable int min_support1_;
mutable int min_support2_;
mutable int64_t max_;
mutable int max_support1_;
mutable int max_support2_;
mutable bool initial_update_;
Solver::IndexEvaluator2 values_;
IntVarIterator* const expr1_iterator_;
IntVarIterator* const expr2_iterator_;
};
IntIntExprFunctionElement::IntIntExprFunctionElement(
Solver* const s, Solver::IndexEvaluator2 values, IntVar* const expr1,
IntVar* const expr2)
: BaseIntExpr(s),
expr1_(expr1),
expr2_(expr2),
min_(0),
min_support1_(-1),
min_support2_(-1),
max_(0),
max_support1_(-1),
max_support2_(-1),
initial_update_(true),
values_(std::move(values)),
expr1_iterator_(expr1_->MakeDomainIterator(true)),
expr2_iterator_(expr2_->MakeDomainIterator(true)) {
CHECK(values_ != nullptr);
}
IntIntExprFunctionElement::~IntIntExprFunctionElement() {}
int64_t IntIntExprFunctionElement::Min() const {
UpdateSupports();
return min_;
}
int64_t IntIntExprFunctionElement::Max() const {
UpdateSupports();
return max_;
}
void IntIntExprFunctionElement::Range(int64_t* lower_bound,
int64_t* upper_bound) {
UpdateSupports();
*lower_bound = min_;
*upper_bound = max_;
}
#define UPDATE_ELEMENT_INDEX_BOUNDS(test) \
const int64_t emin1 = expr1_->Min(); \
const int64_t emax1 = expr1_->Max(); \
const int64_t emin2 = expr2_->Min(); \
const int64_t emax2 = expr2_->Max(); \
int64_t nmin1 = emin1; \
bool found = false; \
while (nmin1 <= emax1 && !found) { \
for (int i = emin2; i <= emax2; ++i) { \
int64_t value = ElementValue(nmin1, i); \
if (test) { \
found = true; \
break; \