25#include "absl/algorithm/container.h"
26#include "absl/container/btree_set.h"
27#include "absl/log/check.h"
28#include "absl/numeric/int128.h"
29#include "absl/random/bit_gen_ref.h"
30#include "absl/random/distributions.h"
31#include "absl/strings/str_cat.h"
32#include "absl/types/span.h"
33#include "google/protobuf/descriptor.h"
37#include "ortools/sat/sat_parameters.pb.h"
45 std::string s = absl::StrCat(num);
47 const int size = s.size();
48 for (
int i = 0;
i < size; ++
i) {
49 if (
i > 0 && (size -
i) % 3 == 0) {
59inline std::string LeftAlign(std::string s,
int size = 16) {
60 if (s.size() >= size)
return s;
65inline std::string RightAlign(std::string s,
int size = 16) {
66 if (s.size() >= size)
return s;
67 return absl::StrCat(std::string(size - s.size(),
' '), s);
72std::string
FormatTable(std::vector<std::vector<std::string>>& table,
74 if (table.size() > 1) {
76 std::sort(table.begin() + 1, table.end());
79 std::vector<int> widths;
80 for (
const std::vector<std::string>& line : table) {
81 if (line.size() > widths.size()) widths.resize(line.size(), spacing);
82 for (
int j = 0; j < line.size(); ++j) {
83 widths[j] = std::max<int>(widths[j], line[j].size() + spacing);
87 for (
int i = 0;
i < table.size(); ++
i) {
88 for (
int j = 0; j < table[
i].size(); ++j) {
89 if (
i == 0 && j == 0) {
91 absl::StrAppend(&output, LeftAlign(table[
i][j], widths[j]));
93 absl::StrAppend(&output, RightAlign(table[
i][j], widths[j]));
96 absl::StrAppend(&output,
"\n");
102 SatParameters* parameters) {
103#if !defined(__PORTABLE_PLATFORM__)
105 const google::protobuf::EnumDescriptor* order_d =
106 SatParameters::VariableOrder_descriptor();
107 parameters->set_preferred_variable_order(
108 static_cast<SatParameters::VariableOrder
>(
109 order_d->value(absl::Uniform(random, 0, order_d->value_count()))
113 const google::protobuf::EnumDescriptor* polarity_d =
114 SatParameters::Polarity_descriptor();
115 parameters->set_initial_polarity(
static_cast<SatParameters::Polarity
>(
116 polarity_d->value(absl::Uniform(random, 0, polarity_d->value_count()))
120 parameters->set_use_phase_saving(absl::Bernoulli(random, 0.5));
121 parameters->set_random_polarity_ratio(absl::Bernoulli(random, 0.5) ? 0.01
123 parameters->set_random_branches_ratio(absl::Bernoulli(random, 0.5) ? 0.01
134void QuotientAndRemainder(int64_t a, int64_t
b, int64_t& q, int64_t& r) {
148 int64_t r[2] = {m, x};
149 int64_t t[2] = {0, 1};
162 for (; r[
i ^ 1] != 0;
i ^= 1) {
163 QuotientAndRemainder(r[
i], r[
i ^ 1], q, r[
i]);
164 t[
i] -= t[
i ^ 1] * q;
168 if (r[
i] != 1)
return 0;
172 if (t[
i] < 0) t[
i] += m;
178 const int64_t r = x % m;
179 return r < 0 ? r + m : r;
187 if (rhs == 0 || mod == 1)
return 0;
188 DCHECK_EQ(std::gcd(std::abs(coeff), mod), 1);
197 CHECK_NE(inverse, 0);
200 const absl::int128 p = absl::int128{inverse} * absl::int128{rhs};
201 return static_cast<int64_t
>(p % absl::int128{mod});
205 int64_t& x0, int64_t& y0) {
208 CHECK_NE(a, std::numeric_limits<int64_t>::min());
209 CHECK_NE(
b, std::numeric_limits<int64_t>::min());
211 const int64_t gcd = std::gcd(std::abs(a), std::abs(
b));
212 if (cte % gcd != 0)
return false;
228 if (cte < 0 && x0 != 0) x0 -= std::abs(
b);
234 const absl::int128 t = absl::int128{cte} - absl::int128{a} * absl::int128{x0};
235 DCHECK_EQ(t % absl::int128{
b}, absl::int128{0});
240 const absl::int128 r = t / absl::int128{
b};
241 DCHECK_LE(r, absl::int128{std::numeric_limits<int64_t>::max()});
242 DCHECK_GE(r, absl::int128{std::numeric_limits<int64_t>::min()});
244 y0 =
static_cast<int64_t
>(r);
251 if (x.IsEmpty() || y.
IsEmpty())
return false;
252 if (a == 0 &&
b == 0) {
256 const int64_t div = cte /
b;
257 if (
b * div != cte)
return false;
261 const int64_t div = cte / a;
262 if (a * div != cte)
return false;
263 return x.Contains(div);
267 const int64_t div = cte / a;
268 if (a * div != cte) {
283 x.AdditionWith(
Domain(-x0))
284 .InverseMultiplicationBy(
b)
288 const Domain z_restricted_d1 =
289 x.AdditionWith(
Domain(-x0)).InverseMultiplicationBy(
b);
290 const Domain z_restricted_d2 =
292 const Domain z_restricted_domain =
294 return !z_restricted_domain.
IsEmpty();
302 static_cast<int64_t
>(std::floor(std::sqrt(
static_cast<double>(a))));
303 while (
CapProd(result, result) > a) --result;
304 while (
CapProd(result + 1, result + 1) <= a) ++result;
311 static_cast<int64_t
>(std::ceil(std::sqrt(
static_cast<double>(a))));
312 while (
CapProd(result, result) < a) ++result;
313 while ((result - 1) * (result - 1) >= a) --result;
319 int64_t result = value /
base *
base;
320 if (value - result >
base / 2) result +=
base;
325 int64_t
base, absl::Span<const int64_t> coeffs,
326 absl::Span<const int64_t> lbs, absl::Span<const int64_t> ubs, int64_t rhs,
329 int64_t max_activity = 0;
331 int64_t min_error = 0;
332 const int num_terms = coeffs.size();
333 if (num_terms == 0)
return false;
334 for (
int i = 0;
i < num_terms; ++
i) {
335 const int64_t coeff = coeffs[
i];
338 max_activity += coeff * ubs[
i];
339 max_x += closest /
base * ubs[
i];
341 const int64_t error = coeff - closest;
343 min_error += error * lbs[
i];
345 min_error += error * ubs[
i];
349 if (max_activity <= rhs) {
356 int64_t max_error_if_invalid = 0;
357 const int64_t slack = max_activity - rhs - 1;
358 for (
int i = 0;
i < num_terms; ++
i) {
359 const int64_t coeff = coeffs[
i];
361 const int64_t error = coeff - closest;
363 max_error_if_invalid += error * ubs[
i];
365 const int64_t lb = std::max(lbs[
i], ubs[
i] - slack / coeff);
366 max_error_if_invalid += error * lb;
381 const int64_t infeasibility_bound =
385 return *new_rhs < infeasibility_bound;
389 const absl::btree_set<LiteralIndex>& processed,
int relevant_prefix_size,
390 std::vector<Literal>* literals) {
391 if (literals->empty())
return -1;
392 if (!processed.contains(literals->back().Index())) {
393 return std::min<int>(relevant_prefix_size, literals->size());
403 int num_processed = 0;
404 int num_not_processed = 0;
405 int target_prefix_size = literals->size() - 1;
406 for (
int i = literals->size() - 1;
i >= 0;
i--) {
407 if (processed.contains((*literals)[
i].Index())) {
411 target_prefix_size =
i;
413 if (num_not_processed >= num_processed)
break;
415 if (num_not_processed == 0)
return -1;
416 target_prefix_size = std::min(target_prefix_size, relevant_prefix_size);
420 std::stable_partition(
421 literals->begin() + target_prefix_size, literals->end(),
422 [&processed](
Literal l) { return processed.contains(l.Index()); });
423 return target_prefix_size;
427 DCHECK(!
input.empty());
429 double total_weight = 0;
430 for (
const double w :
input) {
434 const double weight_point = absl::Uniform(random, 0.0f, total_weight);
435 double total_weight2 = 0;
436 for (
int i = 0;
i <
input.size(); ++
i) {
437 total_weight2 +=
input[
i];
438 if (total_weight2 > weight_point) {
442 return input.size() - 1;
447 average_ = reset_value;
452 average_ += (new_record - average_) / num_records_;
457 average_ = (num_records_ == 1)
459 : (new_record + decaying_factor_ * (average_ - new_record));
463 records_.push_front(record);
464 if (records_.size() > record_limit_) {
470 CHECK_GT(records_.size(), 0);
471 CHECK_LE(percent, 100.0);
472 CHECK_GE(percent, 0.0);
474 const int num_records = records_.size();
475 const double percentile_rank =
476 static_cast<double>(num_records) * percent / 100.0 - 0.5;
477 if (percentile_rank <= 0) {
478 return *absl::c_min_element(records_);
479 }
else if (percentile_rank >= num_records - 1) {
480 return *absl::c_max_element(records_);
482 std::vector<double> sorted_records;
483 sorted_records.assign(records_.begin(), records_.end());
485 DCHECK_GE(num_records, 2);
486 DCHECK_LT(percentile_rank, num_records - 1);
487 const int lower_rank =
static_cast<int>(std::floor(percentile_rank));
488 DCHECK_LT(lower_rank, num_records - 1);
489 auto upper_it = sorted_records.begin() + lower_rank + 1;
493 absl::c_nth_element(sorted_records, upper_it);
494 auto lower_it = std::max_element(sorted_records.begin(), upper_it);
495 return *lower_it + (percentile_rank - lower_rank) * (*upper_it - *lower_it);
502 expanded_sums_.clear();
508 if (value == 0)
return;
509 if (value > bound_)
return;
510 gcd_ = std::gcd(gcd_, value);
511 AddChoicesInternal({value});
516 for (
const int64_t c : choices) {
522 if (current_max_ == bound_)
return;
525 filtered_values_.clear();
526 for (
const int64_t c : choices) {
527 if (c == 0 || c > bound_)
continue;
528 filtered_values_.push_back(c);
529 gcd_ = std::gcd(gcd_, c);
531 if (filtered_values_.empty())
return;
534 std::sort(filtered_values_.begin(), filtered_values_.end());
535 AddChoicesInternal(filtered_values_);
540 DCHECK_GE(max_value, 0);
542 if (coeff == 0 || max_value == 0)
return;
543 if (coeff > bound_)
return;
544 if (current_max_ == bound_)
return;
545 gcd_ = std::gcd(gcd_, coeff);
547 const int64_t num_values =
549 if (num_values > 10) {
552 expanded_sums_.clear();
557 filtered_values_.clear();
558 for (
int multiple = 1; multiple <= num_values; ++multiple) {
559 const int64_t v = multiple * coeff;
561 current_max_ = bound_;
564 filtered_values_.push_back(v);
566 AddChoicesInternal(filtered_values_);
569void MaxBoundedSubsetSum::AddChoicesInternal(absl::Span<const int64_t> values) {
571 if (!sums_.empty() && sums_.size() <= max_complexity_per_add_) {
572 const int old_size = sums_.size();
573 for (
int i = 0;
i < old_size; ++
i) {
574 for (
const int64_t value : values) {
575 const int64_t s = sums_[
i] + value;
576 if (s > bound_)
break;
579 current_max_ = std::max(current_max_, s);
580 if (current_max_ == bound_)
return;
587 if (bound_ <= max_complexity_per_add_) {
588 if (!sums_.empty()) {
589 expanded_sums_.assign(bound_ + 1,
false);
590 for (
const int64_t s : sums_) {
591 expanded_sums_[s] =
true;
597 if (!expanded_sums_.empty()) {
598 for (int64_t
i = bound_ - 1;
i >= 0; --
i) {
599 if (!expanded_sums_[
i])
continue;
600 for (
const int64_t value : values) {
601 if (
i + value > bound_)
break;
603 expanded_sums_[
i + value] =
true;
604 current_max_ = std::max(current_max_,
i + value);
605 if (current_max_ == bound_)
return;
615 current_max_ = bound_;
622 if (candidate > bound_ || current_max_ == bound_)
return current_max_;
624 int64_t current_max = current_max_;
626 if (!sums_.empty()) {
627 for (
const int64_t v : sums_) {
628 if (v + candidate > bound_)
continue;
629 if (v + candidate > current_max) {
630 current_max = v + candidate;
631 if (current_max == bound_)
return current_max;
638 if (!expanded_sums_.empty()) {
639 const int64_t min_useful = std::max<int64_t>(0, current_max_ - candidate);
640 const int64_t max_useful = bound_ - candidate;
641 for (int64_t v = max_useful; v >= min_useful; --v) {
642 if (expanded_sums_[v])
return v + candidate;
649 absl::Span<const Domain> domains, absl::Span<const int64_t> coeffs,
650 absl::Span<const int64_t> costs,
const Domain& rhs) {
651 const int num_vars = domains.size();
652 if (num_vars == 0)
return {};
654 int64_t min_activity = 0;
655 int64_t max_domain_size = 0;
656 for (
int i = 0;
i < num_vars; ++
i) {
657 max_domain_size = std::max(max_domain_size, domains[
i].Size());
659 min_activity += coeffs[
i] * domains[
i].Min();
661 min_activity += coeffs[
i] * domains[
i].Max();
670 const int64_t num_values = rhs.
Max() - min_activity + 1;
671 if (num_values < 0) {
680 const int64_t max_work_per_variable = std::min(num_values, max_domain_size);
681 if (rhs.
Max() - min_activity > 1e6)
return {};
682 if (num_vars * num_values * max_work_per_variable > 1e8)
return {};
688 for (
int i = 0;
i < num_vars; ++
i) {
690 domains_.push_back(domains[
i].AdditionWith(
Domain(-domains[
i].Min())));
691 coeffs_.push_back(coeffs[
i]);
692 costs_.push_back(costs[
i]);
695 domains[
i].Negation().AdditionWith(
Domain(domains[
i].Max())));
696 coeffs_.push_back(-coeffs[
i]);
697 costs_.push_back(-costs[
i]);
705 for (
int i = 0;
i < num_vars; ++
i) {
717 int64_t num_values,
const Domain& rhs) {
718 const int num_vars = domains_.size();
721 var_activity_states_.assign(num_vars, std::vector<State>(num_values));
724 for (
const int64_t v : domains_[0].Values()) {
725 const int64_t value = v * coeffs_[0];
727 if (value >= num_values)
break;
728 var_activity_states_[0][value].cost = v * costs_[0];
729 var_activity_states_[0][value].value = v;
733 for (
int i = 1;
i < num_vars; ++
i) {
734 const std::vector<State>& prev = var_activity_states_[
i - 1];
735 std::vector<State>& current = var_activity_states_[
i];
736 for (
int prev_value = 0; prev_value < num_values; ++prev_value) {
737 if (prev[prev_value].cost == std::numeric_limits<int64_t>::max()) {
740 for (
const int64_t v : domains_[
i].Values()) {
741 const int64_t value = prev_value + v * coeffs_[
i];
743 if (value >= num_values)
break;
744 const int64_t new_cost = prev[prev_value].cost + v * costs_[
i];
745 if (new_cost < current[value].cost) {
746 current[value].cost = new_cost;
747 current[value].value = v;
756 int64_t best_cost = std::numeric_limits<int64_t>::max();
757 int64_t best_activity;
758 for (
int v = 0; v < num_values; ++v) {
761 if (var_activity_states_.back()[v].cost < best_cost) {
762 best_cost = var_activity_states_.back()[v].cost;
767 if (best_cost == std::numeric_limits<int64_t>::max()) {
768 result.infeasible =
true;
773 result.solution.resize(num_vars);
774 int64_t current_activity = best_activity;
775 for (
int i = num_vars - 1;
i >= 0; --
i) {
776 const int64_t var_value = var_activity_states_[
i][current_activity].value;
777 result.solution[
i] = var_value;
778 current_activity -= coeffs_[
i] * var_value;
786class CliqueDecomposition {
788 CliqueDecomposition(
const std::vector<std::vector<int>>& graph,
789 absl::BitGenRef random, std::vector<int>* buffer)
790 : graph_(graph), random_(random), buffer_(buffer) {
791 const int n = graph.size();
792 permutation_.resize(n);
796 for (
int i = 0;
i < n; ++
i) permutation_[
i] =
i;
803 void DecomposeGreedily() {
804 decomposition_.clear();
807 const int n = graph_.size();
808 taken_.assign(n,
false);
809 temp_.assign(n,
false);
811 int buffer_index = 0;
812 for (
const int i : permutation_) {
813 if (taken_[
i])
continue;
816 const int start = buffer_index;
818 (*buffer_)[buffer_index++] =
i;
821 for (
const int c : graph_[
i]) {
822 if (!taken_[c]) candidates_.push_back(c);
824 while (!candidates_.empty()) {
826 int next = candidates_.front();
827 for (
const int n : candidates_) {
828 if (permutation_[n] < permutation_[next]) next = n;
833 (*buffer_)[buffer_index++] = next;
837 for (
const int head : graph_[next]) temp_[head] =
true;
839 for (
const int c : candidates_) {
840 if (taken_[c])
continue;
841 if (!temp_[c])
continue;
842 candidates_[new_size++] =
c;
844 candidates_.resize(new_size);
845 for (
const int head : graph_[next]) temp_[head] =
false;
849 decomposition_.push_back(
850 absl::MakeSpan(buffer_->data() + start, buffer_index - start));
852 DCHECK_EQ(buffer_index, n);
862 if (absl::Bernoulli(random_, 0.5)) {
863 std::reverse(decomposition_.begin(), decomposition_.end());
865 std::shuffle(decomposition_.begin(), decomposition_.end(), random_);
869 for (
const absl::Span<const int> clique : decomposition_) {
870 for (
const int i : clique) {
871 permutation_[out_index++] =
i;
876 const std::vector<absl::Span<int>>& decomposition()
const {
877 return decomposition_;
881 const std::vector<std::vector<int>>& graph_;
882 absl::BitGenRef random_;
883 std::vector<int>* buffer_;
885 std::vector<absl::Span<int>> decomposition_;
886 std::vector<int> candidates_;
887 std::vector<int> permutation_;
888 std::vector<bool> taken_;
889 std::vector<bool> temp_;
895 const std::vector<std::vector<int>>& graph, absl::BitGenRef random,
896 std::vector<int>* buffer) {
897 CliqueDecomposition decomposer(graph, random, buffer);
898 for (
int pass = 0; pass < 10; ++pass) {
899 decomposer.DecomposeGreedily();
900 if (decomposer.decomposition().size() == 1)
break;
901 decomposer.ChangeOrder();
903 return decomposer.decomposition();
907 absl::Span<const int64_t> elements, int64_t maximum_sum,
908 bool abort_if_maximum_reached) {
911 for (
const int64_t e : elements) {
913 if (e == 0 || e > maximum_sum)
continue;
917 if (sums_.size() == maximum_sum + 1)
return sums_;
920 if (abort_if_maximum_reached && sums_.back() == maximum_sum)
return sums_;
926 const int size = sums_.size();
927 const int64_t*
const data = sums_.data();
928 int64_t last_pushed = -1;
931 const int64_t a = data[
i];
932 const int64_t
b = data[j] + e;
942 if (to_push == last_pushed)
continue;
943 if (to_push > maximum_sum) {
947 last_pushed = to_push;
948 new_sums_.push_back(to_push);
956 for (; j < size; ++j) {
957 const int64_t to_push = data[j] + e;
958 if (to_push == last_pushed)
continue;
959 if (to_push > maximum_sum)
break;
960 last_pushed = to_push;
961 new_sums_.push_back(to_push);
963 std::swap(sums_, new_sums_);
970 double estimate = std::numeric_limits<double>::infinity();
971 if (num_elements < 100) {
972 estimate = 2 * pow(2.0, num_elements / 2);
974 return std::min(estimate,
static_cast<double>(bin_size) *
975 static_cast<double>(num_elements));
979 absl::Span<const int64_t> elements, int64_t bin_size) {
981 if (elements.empty())
return 0;
982 if (elements.size() == 1) {
983 if (elements[0] > bin_size)
return 0;
988 const int middle = elements.size() / 2;
989 const auto span_a = sums_a_.Compute(elements.subspan(0, middle), bin_size,
991 if (span_a.back() == bin_size)
return bin_size;
993 const auto span_b = sums_b_.Compute(elements.subspan(middle), bin_size,
995 if (span_b.back() == bin_size)
return bin_size;
1000 CHECK(!span_a.empty());
1001 CHECK(!span_b.empty());
1002 int j = span_b.size() - 1;
1003 for (
int i = 0;
i < span_a.size(); ++
i) {
1004 while (j >= 0 && span_a[
i] + span_b[j] > bin_size) --j;
1005 result = std::max(result, span_a[
i] + span_b[j]);
1006 if (result == bin_size)
return bin_size;
Domain IntersectionWith(const Domain &domain) const
bool Contains(int64_t value) const
Domain AdditionWith(const Domain &domain) const
Domain InverseMultiplicationBy(int64_t coeff) const
static IntegralType CeilOfRatio(IntegralType numerator, IntegralType denominator)
static IntegralType FloorOfRatio(IntegralType numerator, IntegralType denominator)
Result Solve(absl::Span< const Domain > domains, absl::Span< const int64_t > coeffs, absl::Span< const int64_t > costs, const Domain &rhs)
void AddData(double new_record)
void Reset(double reset_value)
Sets the number of records to 0 and average to 'reset_value'.
void AddData(double new_record)
double ComplexityEstimate(int num_elements, int64_t bin_size)
int64_t MaxSubsetSum(absl::Span< const int64_t > elements, int64_t bin_size)
void AddChoices(absl::Span< const int64_t > choices)
int64_t MaxIfAdded(int64_t candidate) const
Returns the updated max if value was added to the subset-sum.
void Add(int64_t value)
Add a value to the base set for which subset sums will be taken.
void Reset(int64_t bound)
void AddMultiples(int64_t coeff, int64_t max_value)
Adds [0, coeff, 2 * coeff, ... max_value * coeff].
void AddRecord(double record)
double GetPercentile(double percent)
absl::Span< const int64_t > Compute(absl::Span< const int64_t > elements, int64_t maximum_sum, bool abort_if_maximum_reached=false)
void RandomizeDecisionHeuristic(absl::BitGenRef random, SatParameters *parameters)
Randomizes the decision heuristic of the given SatParameters.
int64_t ProductWithModularInverse(int64_t coeff, int64_t mod, int64_t rhs)
bool SolveDiophantineEquationOfSizeTwo(int64_t &a, int64_t &b, int64_t &cte, int64_t &x0, int64_t &y0)
int64_t FloorSquareRoot(int64_t a)
The argument must be non-negative.
int64_t CeilSquareRoot(int64_t a)
int64_t ModularInverse(int64_t x, int64_t m)
int WeightedPick(absl::Span< const double > input, absl::BitGenRef random)
std::string FormatCounter(int64_t num)
Prints a positive number with separators for easier reading (ex: 1'348'065).
bool DiophantineEquationOfSizeTwoHasSolutionInDomain(const Domain &x, int64_t a, const Domain &y, int64_t b, int64_t cte)
int64_t ClosestMultiple(int64_t value, int64_t base)
int64_t PositiveMod(int64_t x, int64_t m)
Just returns x % m but with a result always in [0, m).
bool LinearInequalityCanBeReducedWithClosestMultiple(int64_t base, absl::Span< const int64_t > coeffs, absl::Span< const int64_t > lbs, absl::Span< const int64_t > ubs, int64_t rhs, int64_t *new_rhs)
int MoveOneUnprocessedLiteralLast(const absl::btree_set< LiteralIndex > &processed, int relevant_prefix_size, std::vector< Literal > *literals)
std::vector< absl::Span< int > > AtMostOneDecomposition(const std::vector< std::vector< int > > &graph, absl::BitGenRef random, std::vector< int > *buffer)
std::string FormatTable(std::vector< std::vector< std::string > > &table, int spacing)
In SWIG mode, we don't want anything besides these top-level includes.
int64_t CapProd(int64_t x, int64_t y)
trees with all degrees equal w the current value of w
static int input(yyscan_t yyscanner)
std::vector< int64_t > solution