2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
40
41
42
43
46
47
51inline void throw_assertion_error(
const std::string &condition,
52 const std::string &msg) {
53 throw std::runtime_error(
"tgen: " + msg +
" (assertion `" + condition +
56inline void throw_assertion_error(
const std::string &condition) {
57 throw std::runtime_error(
"tgen: assertion `" + condition +
"` failed");
59inline std::runtime_error error(
const std::string &msg) {
60 return std::runtime_error(
"tgen: " + msg);
62inline std::runtime_error contradiction_error(
const std::string &type,
63 const std::string &msg =
"") {
65 std::string error_msg =
"invalid " + type +
" (contradicting constraints)";
67 error_msg +=
": " + msg;
68 return error(error_msg);
71std::runtime_error there_is_no_in_range_error(
const std::string &type, T l,
73 return error(
"there is no " + type +
" in range [" + std::to_string(l) +
74 ", " + std::to_string(r) +
"]");
77std::runtime_error there_is_no_upto_error(
const std::string &type, T r) {
78 return error(
"there is no " + type +
" up to " + std::to_string(r));
80inline void tgen_ensure_against_bug(
bool cond) {
82 throw std::runtime_error(
83 "tgen: THERE IS A BUG IN TGEN; PLEASE CONTACT MAINTAINERS");
87#define tgen_ensure(cond, ...)
89 tgen::_detail::throw_assertion_error(#cond, ##__VA_ARGS__);
92inline bool registered =
false;
93inline void ensure_registered() {
95 "tgen was not registered! You should call "
96 "tgen::register_gen(argc, argv) before running tgen functions");
102
103
110template <
typename T,
typename =
void>
struct is_container : std::false_type {};
112struct is_container<T, std::void_t<
typename T::value_type,
113 decltype(std::begin(std::declval<T>())),
114 decltype(std::end(std::declval<T>()))>>
116template <>
struct is_container<std::string> : std::false_type {};
118template <
typename T>
struct is_pair : std::false_type {};
119template <
typename A,
typename B>
120struct is_pair<std::pair<A, B>> : std::true_type {};
122template <
typename T>
struct is_tuple : std::false_type {};
123template <
typename... Ts>
124struct is_tuple<std::tuple<Ts...>> : std::true_type {};
137template <
typename A,
typename B>
142template <
typename... Ts>
152 template <
typename T> print(
const T &x) {
153 std::ostringstream oss;
157 template <
typename T> print(
const std::initializer_list<T> &il) {
158 std::ostringstream oss;
159 write(oss, std::vector<T>(il.begin(), il.end()));
162 template <
typename T>
163 print(
const std::initializer_list<std::initializer_list<T>> &il) {
164 std::ostringstream oss;
165 std::vector<std::vector<T>> mat;
166 for (
const auto &i : il)
172 template <
typename T>
void write(std::ostream &os,
const T &x) {
173 if constexpr (_detail::
is_pair<T>::value) {
183 }
else if constexpr (_detail::
is_tuple<T>::value)
185 else if constexpr (_detail::is_container<T>::value)
186 write_container(os, x);
192 template <
typename C>
void write_container(std::ostream &os,
const C &c) {
195 for (
const auto &e : c) {
204 template <
typename Tuple, size_t... I>
205 void write_tuple_impl(std::ostream &os,
const Tuple &tp,
206 std::index_sequence<I...>) {
208 ((os << (first ? (first =
false,
"")
211 write(os, std::get<I>(tp))),
214 template <
typename T>
void write_tuple(std::ostream &os,
const T &tp) {
215 write_tuple_impl(os, tp,
216 std::make_index_sequence<std::tuple_size<T>::value>{});
219 friend std::ostream &operator<<(std::ostream &out,
const print &pr) {
225template <
typename T>
inline print println(
const T &x) {
230template <
typename T>
inline print println(
const std::initializer_list<T> &il) {
237println(
const std::initializer_list<std::initializer_list<T>> &il) {
244
245
249inline std::mt19937 rng;
252template <
typename Gen>
struct gen_base {
254 template <
typename Pred,
typename... Args>
255 auto gen_until(Pred predicate,
int max_tries, Args &&...args)
const {
256 for (
int i = 0; i < max_tries; ++i) {
257 auto inst =
static_cast<
const Gen *>(
this)->gen(
258 std::forward<Args>(args)...);
264 throw error(
"could not generate instance matching predicate");
266 template <
typename Pred,
typename T,
typename... Args>
267 auto gen_until(Pred predicate,
int max_tries, std::initializer_list<T> il,
268 Args &&...args)
const {
269 return gen_until(predicate, max_tries, std::vector<T>(il),
270 std::forward<Args>(args)...);
274 friend std::ostream &operator<<(std::ostream &out,
const gen_base &) {
277 "you cannot print a generator. Maybe you forgot to call `gen()`?");
282template <
typename T,
typename =
void>
285struct is_associative_container<
286 T, std::void_t<
typename T::key_type,
typename T::key_compare>>
292template <
typename T,
typename =
void>
295struct is_generator_instance<T, std::void_t<
typename T::_tgen_instance_tag>>
296 : std::is_same<
typename T::_tgen_instance_tag, generator_instance_tag> {};
302template <
typename T> T
next(T l, T r) {
303 _detail::ensure_registered();
304 tgen_ensure(l <= r,
"range for `next` bust be valid");
305 if constexpr (std::is_integral_v<T>)
306 return std::uniform_int_distribution<T>(l, r)(_detail::rng);
307 else if constexpr (std::is_floating_point_v<T>)
308 return std::uniform_real_distribution<T>(l, r)(_detail::rng);
310 throw _detail::error(
"invalid type for next (" +
311 std::string(
typeid(T).name()) +
")");
316template <
typename It>
void shuffle(It first, It last) {
320 for (It i = first + 1; i != last; ++i)
321 std::iter_swap(i, first + next(0,
static_cast<
int>(i - first)));
327 std::enable_if_t<!_detail::is_associative_container<C>::value
and
328 !_detail::is_generator_instance<C>::value,
331 auto new_container = container;
332 shuffle(new_container.begin(), new_container.end());
333 return new_container;
335template <
typename C, std::enable_if_t<
336 _detail::is_associative_container<C>::value,
int> = 0>
337[[nodiscard]] std::vector<
typename C::value_type> shuffled(
const C &container) {
338 return shuffled(std::vector<
typename C::value_type>(container.begin(),
342[[nodiscard]] std::vector<T> shuffled(
const std::initializer_list<T> &il) {
343 return shuffled(std::vector<T>(il.begin(), il.end()));
350 std::enable_if_t<_detail::is_generator_instance<Inst>::value,
int> = 0>
352 Inst new_inst = inst;
353 tgen::shuffle(new_inst.vec_.begin(), new_inst.vec_.end());
360 int size = std::distance(first, last);
362 std::advance(it, next(0, size - 1));
369 std::enable_if_t<!_detail::is_generator_instance<C>::value,
int> = 0>
371 return any(container.begin(), container.end());
373template <
typename T> T any(
const std::initializer_list<T> &il) {
374 return any(std::vector<T>(il.begin(), il.end()));
381 std::enable_if_t<_detail::is_generator_instance<Inst>::value,
int> = 0>
383 return inst.vec_[next<
int>(0, inst.vec_.size() - 1)];
389 std::enable_if_t<!_detail::is_generator_instance<C>::value,
int> = 0>
391 tgen_ensure(0 < k
and k <=
static_cast<
int>(container.size()),
392 "number of elements to choose must be valid");
393 std::vector<
typename C::value_type> new_vec;
395 int need = k, left = container.size();
396 for (
auto cur_it = container.begin(); cur_it != container.end(); ++cur_it) {
397 if (next(1, left--) <= need) {
398 new_container.insert(new_container.end(), *cur_it);
402 return new_container;
405std::vector<T> choose(
int k,
const std::initializer_list<T> &il) {
406 return choose(k, std::vector<T>(il.begin(), il.end()));
414 std::enable_if_t<_detail::is_generator_instance<Inst>::value,
int> = 0>
416 tgen_ensure(0 < k
and k <=
static_cast<
int>(inst.vec_.size()),
417 "number of elements to choose must be valid");
418 std::vector<
typename Inst::value_type> new_vec;
420 for (
int i = 0; need > 0; ++i) {
421 int left = inst.vec_.size() - i;
422 if (next(1, left) <= need) {
423 new_vec.push_back(inst.vec_[i]);
427 return Inst(new_vec);
431
432
433
434
437
438
439
440
441
442
443
444
445
446
447
448
449
453inline std::vector<std::string>
455inline std::map<std::string, std::string>
458template <
typename T> T get_opt(
const std::string &value) {
460 if constexpr (std::is_same_v<T,
bool>) {
461 if (value ==
"true" or value ==
"1")
463 if (value ==
"false" or value ==
"0")
465 }
else if constexpr (std::is_integral_v<T>) {
466 if constexpr (std::is_unsigned_v<T>)
467 return static_cast<T>(std::stoull(value));
469 return static_cast<T>(std::stoll(value));
470 }
else if constexpr (std::is_floating_point_v<T>)
471 return static_cast<T>(std::stold(value));
477 throw _detail::error(
"invalid value `" + value +
"` for type " +
481inline void parse_opts(
int argc,
char **argv) {
484 for (
int i = 1; i < argc; ++i) {
485 std::string key(argv[i]);
489 "invalid opt (" + std::string(argv[i]) +
")");
490 if (
'0' <= key[1]
and key[1] <=
'9') {
492 _detail::pos_opts.push_back(key);
500 _detail::pos_opts.push_back(key);
507 "invalid opt (" + std::string(argv[i]) +
")");
517 std::size_t eq = key.find(
'=');
518 if (eq != std::string::npos) {
520 std::string value = key.substr(eq + 1);
521 key = key.substr(0, eq);
523 "expected non-empty key/value in opt (" +
524 std::string(argv[1]));
526 "cannot have repeated keys");
527 _detail::named_opts[key] = value;
531 "cannot have repeated keys");
533 _detail::named_opts[key] = std::string(argv[i + 1]);
539inline void set_seed(
int argc,
char **argv) {
540 std::vector<uint32_t> seed;
543 for (
int i = 1; i < argc; ++i) {
545 int size_pos = seed.size();
547 for (
char *s = argv[i]; *s !=
'\0'; ++s) {
552 std::seed_seq seq(seed.begin(), seed.end());
553 _detail::rng.seed(seq);
560 tgen::_detail::ensure_registered();
561 return 0 <= index
and index < _detail::pos_opts.size();
566 tgen::_detail::ensure_registered();
567 return _detail::named_opts.count(key) != 0;
572template <
typename T,
typename Key>
573T
opt(
const Key &key, std::optional<T> default_value = std::nullopt) {
574 tgen::_detail::ensure_registered();
575 if constexpr (std::is_same_v<Key,
int>) {
578 return *default_value;
579 throw _detail::error(
"cannot find key with index " +
580 std::to_string(key));
582 return _detail::get_opt<T>(_detail::pos_opts[key]);
586 return *default_value;
587 throw _detail::error(
"cannot find key with key " +
590 return _detail::get_opt<T>(_detail::named_opts[key]);
596 _detail::set_seed(argc, argv);
598 _detail::pos_opts.clear();
599 _detail::named_opts.clear();
600 _detail::parse_opts(argc, argv);
602 _detail::registered =
true;
606
607
608
609
612
613
617 T value_l_, value_r_;
623 std::vector<std::pair<T, T>> val_range_;
624 std::vector<std::vector<
int>> neigh_;
625 std::vector<std::set<
int>>
626 distinct_constraints_;
630 : size_(size), value_l_(value_l), value_r_(value_r),
neigh_(
size) {
632 tgen_ensure(value_l_ <= value_r_,
"value range must be valid");
633 for (
int i = 0; i < size_; ++i)
634 val_range_.emplace_back(value_l_, value_r_);
641 tgen_ensure(!values.empty(),
"value set must be non-empty");
642 value_l_ = 0, value_r_ = values.size() - 1;
643 for (
int i = 0; i < size_; ++i)
644 val_range_.emplace_back(value_l_, value_r_);
646 for (T value : values_)
647 value_idx_in_set_[value] = idx++;
652 tgen_ensure(0 <= idx
and idx < size_,
"index must be valid");
653 if (values_.size() == 0) {
654 auto &[left, right] = val_range_[idx];
655 if (left == right
and value_l_ != value_r_) {
657 "must not set to two different values");
660 "value must be in the defined range");
662 left = right = value;
665 "value must be in the set of values");
666 auto &[left, right] = val_range_[idx];
667 int new_val = value_idx_in_set_[value];
669 "must not set to two different values");
670 left = right = new_val;
678 std::max(idx_1, idx_2) < size_,
679 "indices must be valid");
683 neigh_[idx_1].push_back(idx_2);
684 neigh_[idx_2].push_back(idx_1);
690 tgen_ensure(0 <= left
and left <= right
and right < size_,
691 "range indices bust be valid");
692 for (
int i = left; i < right; ++i)
701 if (!indices.empty())
702 distinct_constraints_.push_back(indices);
708 std::set<
int> indices = {idx_1, idx_2};
714 std::vector<
int> indices(size_);
715 std::iota(indices.begin(), indices.end(), 0);
716 return distinct(std::set<
int>(indices.begin(), indices.end()));
723 using value_type = T;
728 instance(
const std::initializer_list<T> &il)
729 : vec_(il.begin(), il.end()) {}
732 int size()
const {
return vec_.size(); }
735 T &operator[](
int idx) {
return vec_[idx]; }
736 const T &
operator[](
int idx)
const {
return vec_[idx]; }
741 std::sort(vec_.begin(), vec_.end());
748 std::reverse(vec_.begin(), vec_.end());
755 std::vector<T> new_vec = vec_;
756 for (
int i = 0; i < rhs
.size(); ++i)
757 new_vec.push_back(rhs[i]);
762 friend std::ostream &operator<<(std::ostream &out,
764 for (
int i = 0; i < inst.size(); ++i) {
779 generate_distinct_values(
int k,
const std::set<T> &forbidden_values)
const {
780 for (
auto forbidden : forbidden_values)
781 tgen_ensure(value_l_ <= forbidden
and forbidden <= value_r_);
786 T num_available = (value_r_ - value_l_ + 1) - forbidden_values.size();
787 if (num_available < k)
788 throw _detail::error(
789 "failed to generate sequence: complex constraints");
790 std::map<T, T> virtual_list;
791 std::vector<T> gen_list;
792 for (
int i = 0; i < k; ++i) {
793 T j = next<T>(i, num_available - 1);
794 T vj = virtual_list.count(j) ? virtual_list[j] : j;
795 T vi = virtual_list.count(i) ? virtual_list[i] : i;
797 virtual_list[j] = vi, virtual_list[i] = vj;
799 gen_list.push_back(virtual_list[i]);
804 for (T &value : gen_list)
809 std::vector<std::pair<T,
int>> values_sorted;
810 for (std::size_t i = 0; i < gen_list.size(); ++i)
811 values_sorted.emplace_back(gen_list[i], i);
813 std::sort(values_sorted.begin(), values_sorted.end());
814 auto cur_it = forbidden_values.begin();
815 int smaller_forbidden_count = 0;
816 for (
auto [val, idx] : values_sorted) {
817 while (cur_it != forbidden_values.end()
and
818 *cur_it <= val + smaller_forbidden_count)
819 ++cur_it, ++smaller_forbidden_count;
820 gen_list[idx] += smaller_forbidden_count;
829 std::vector<T> vec(size_);
830 std::vector<
bool> defined_idx(
833 std::vector<
int> comp_id(size_, -1);
834 std::vector<std::vector<
int>> comp(size_);
838 auto define_comp = [&](
int cur_comp, T val) {
839 for (
int idx : comp[cur_comp]) {
842 defined_idx[idx] =
true;
848 std::vector<
bool> vis(size_,
false);
849 for (
int idx = 0; idx < size_; ++idx)
852 bool value_defined =
false;
856 std::queue<
int> q({idx});
858 std::vector<
int> component;
860 int cur_idx = q.front();
863 component.push_back(cur_idx);
866 auto [l, r] = val_range_[cur_idx];
868 if (!value_defined) {
870 value_defined =
true;
872 }
else if (new_value != l) {
874 throw _detail::contradiction_error(
876 "tried to set value to `" +
877 std::to_string(new_value) +
878 "`, but it was already set as `" +
879 std::to_string(l) +
"`");
883 for (
int nxt_idx : neigh_[cur_idx]) {
892 for (
int cur_idx : component) {
893 comp_id[cur_idx] = comp_count;
894 comp[comp_id[cur_idx]].push_back(cur_idx);
899 define_comp(comp_count, new_value);
906 std::vector<std::set<
int>> distinct_containing_comp_idx(comp_count);
909 for (
const std::set<
int> &distinct : distinct_constraints_) {
911 if (
static_cast<uint64_t>(distinct.size() - 1) +
912 static_cast<uint64_t>(value_l_) >
913 static_cast<uint64_t>(value_r_))
914 throw _detail::contradiction_error(
916 "tried to generate " + std::to_string(distinct.size()) +
917 " distinct values, but the maximum is " +
918 std::to_string(value_r_ - value_l_ + 1));
922 std::set<
int> comp_ids;
923 for (
int idx : distinct) {
924 if (comp_ids.count(comp_id[idx]))
925 throw _detail::contradiction_error(
926 "sequence",
"tried to set two indices as equal and "
928 comp_ids.insert(comp_id[idx]);
930 distinct_containing_comp_idx[comp_id[idx]].insert(dist_id);
937 for (
auto &distinct_containing : distinct_containing_comp_idx)
938 if (distinct_containing.size() >= 3)
939 throw _detail::error(
940 "failed to generate sequence: complex constraints");
942 std::vector<
bool> vis_distinct(distinct_constraints_.size(),
false);
943 std::vector<
bool> initially_defined_comp_idx(comp_count,
false);
946 auto define_tree = [&](
int distinct_id) {
951 std::set<T> defined_values;
952 for (
int idx : distinct_constraints_[distinct_id])
953 if (defined_idx[idx]) {
956 if (defined_values.count(vec[idx]))
957 throw _detail::contradiction_error(
959 "tried to set two indices as equal and different");
961 defined_values.insert(vec[idx]);
966 int new_value_count =
967 distinct_constraints_[distinct_id].size() -
968 static_cast<
int>(defined_values.size());
969 std::vector<T> generated_values =
970 generate_distinct_values(new_value_count, defined_values);
971 auto val_it = generated_values.begin();
972 for (
int idx : distinct_constraints_[distinct_id])
973 if (defined_idx[idx]) {
976 initially_defined_comp_idx[comp_id[idx]] =
false;
978 define_comp(comp_id[idx], *val_it);
984 std::queue<std::pair<
int,
int>> q;
985 q.emplace(distinct_id, -1);
986 vis_distinct[distinct_id] =
true;
988 auto [cur_distinct, parent] = q.front();
991 std::set<
int> neigh_distinct;
992 for (
int idx : distinct_constraints_[cur_distinct])
993 for (
int nxt_distinct :
994 distinct_containing_comp_idx[comp_id[idx]]) {
995 if (nxt_distinct == cur_distinct
or
996 nxt_distinct == parent)
1000 if (vis_distinct[nxt_distinct])
1001 throw _detail::error(
"failed to generate sequence: "
1002 "complex constraints");
1004 neigh_distinct.insert(nxt_distinct);
1007 for (
int nxt_distinct : neigh_distinct) {
1008 vis_distinct[nxt_distinct] =
true;
1009 q.emplace(nxt_distinct, cur_distinct);
1012 std::set<T> nxt_defined_values;
1013 for (
int idx2 : distinct_constraints_[nxt_distinct])
1014 if (defined_idx[idx2]) {
1018 if (initially_defined_comp_idx[comp_id[idx2]])
1019 throw _detail::error(
1020 "failed to generate sequence: "
1021 "complex constraints");
1023 nxt_defined_values.insert(vec[idx2]);
1025 int new_value_count =
1026 distinct_constraints_[nxt_distinct].size() -
1027 static_cast<
int>(nxt_defined_values.size());
1028 std::vector<T> generated_values = generate_distinct_values(
1029 new_value_count, nxt_defined_values);
1030 auto val_it = generated_values.begin();
1031 for (
int idx2 : distinct_constraints_[nxt_distinct])
1032 if (!defined_idx[idx2]) {
1033 define_comp(comp_id[idx2], *val_it);
1045 std::vector<std::pair<
int,
int>> defined_cnt_and_distinct_idx;
1047 for (
const std::set<
int> &distinct : distinct_constraints_) {
1048 int defined_cnt = 0;
1049 for (
int idx : distinct)
1050 if (defined_idx[idx]) {
1052 initially_defined_comp_idx[comp_id[idx]] =
true;
1054 defined_cnt_and_distinct_idx.emplace_back(defined_cnt, dist_id);
1058 std::sort(defined_cnt_and_distinct_idx.rbegin(),
1059 defined_cnt_and_distinct_idx.rend());
1060 for (
auto [defined_cnt, distinct_idx] :
1061 defined_cnt_and_distinct_idx)
1062 if (!vis_distinct[distinct_idx])
1063 define_tree(distinct_idx);
1067 for (std::size_t dist_id = 0; dist_id < distinct_constraints_.size();
1069 if (!vis_distinct[dist_id])
1070 define_tree(dist_id);
1075 for (
int idx = 0; idx < size_; ++idx)
1076 if (!defined_idx[idx])
1077 define_comp(comp_id[idx], next<T>(value_l_, value_r_));
1079 if (!values_.empty()) {
1081 std::vector<T> value_vec(values_.begin(), values_.end());
1083 val = value_vec[val];
1091
1092
1093
1094
1097
1098
1099
1100
1104 std::vector<std::pair<
int,
int>> sets;
1113 tgen_ensure(0 <= idx
and idx < size_,
"index must be valid");
1114 sets.emplace_back(idx, value);
1123 std::vector<
int> vec_;
1127 tgen_ensure(!vec_.empty(),
"permutation cannot be empty");
1128 std::vector<
bool> vis(vec_.size(),
false);
1129 for (
int i = 0; i <
size(); ++i) {
1131 vec_[i] <
static_cast<
int>(vec_.size()),
1132 "permutation values must be from `0` to `size-1`");
1134 "cannot have repeated values in permutation");
1135 vis[vec_[i]] =
true;
1138 instance(
const std::initializer_list<
int> &il)
1139 : instance(std::vector<
int>(il.begin(), il.end())) {}
1142 int size()
const {
return vec_.size(); }
1146 const int &operator[](
int idx)
const {
return vec_[idx]; }
1151 std::vector<
bool> vis(
size(),
false);
1154 for (
int i = 0; i <
size(); ++i)
1157 for (
int j = i; !vis[j]; j = vec_[j])
1161 return ((
size() - cycles) % 2 == 0) ? +1 : -1;
1167 for (
int i = 0; i < size(); ++i)
1175 std::reverse(vec_.begin(), vec_.end());
1182 std::vector<
int> inv(
size());
1183 for (
int i = 0; i < size(); ++i)
1197 friend std::ostream &operator<<(std::ostream &out,
1199 for (
int i = 0; i < inst
.size(); ++i) {
1202 out << inst[i] + inst.add_1_;
1214 std::vector<
int> idx_to_val(size_, -1), val_to_idx(size_, -1);
1215 for (
auto [idx, val] : sets) {
1217 "value in permutation must be in [0, " +
1218 std::to_string(size_) +
")");
1220 if (idx_to_val[idx] != -1) {
1222 "cannot set an idex to two different values");
1224 idx_to_val[idx] = val;
1226 if (val_to_idx[val] != -1) {
1228 "cannot set two indices to the same value");
1230 val_to_idx[val] = idx;
1233 std::vector<
int> perm(size_);
1234 std::iota(perm.begin(), perm.end(), 0);
1235 shuffle(perm.begin(), perm.end());
1237 for (
int &i : idx_to_val)
1240 while (val_to_idx[perm[cur_idx]] != -1)
1242 i = perm[cur_idx++];
1251 size_ == std::accumulate(cycle_sizes.begin(), cycle_sizes.end(), 0),
1252 "cycle sizes must add up to size of permutation");
1255 std::vector<
int> order(size_);
1256 std::iota(order.begin(), order.end(), 0);
1257 shuffle(order.begin(), order.end());
1259 std::vector<std::vector<
int>> cycles;
1260 for (
int cycle_size : cycle_sizes) {
1261 cycles.emplace_back();
1262 for (
int i = 0; i < cycle_size; ++i)
1263 cycles.back().push_back(order[idx++]);
1267 std::vector<
int> perm(size_, -1);
1268 for (
const std::vector<
int> &cycle : cycles) {
1269 int cur_size = cycle.size();
1270 for (
int i = 0; i < cur_size; ++i)
1271 perm[cycle[i]] = cycle[(i + 1) % cur_size];
1279
1280
1281
1282
1287inline int ctzll(uint64_t x) {
1290 static const unsigned char index64[64] = {
1291 0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
1292 62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
1293 63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
1294 51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12};
1295 return index64[((x & -x) * 0x022FDD63CC95386D) >> 58];
1298inline uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t m) {
1299 return static_cast<
unsigned __int128>(a) * b % m;
1304inline uint64_t expo_mod(uint64_t x, uint64_t y, uint64_t m) {
1307 uint64_t ans = expo_mod(mul_mod(x, x, m), y / 2, m);
1308 return y % 2 ? mul_mod(x, ans, m) : ans;
1317 if (n == 2
or n == 3)
1322 uint64_t r = _detail::ctzll(n - 1), d = n >> r;
1324 for (
int a : {2, 325, 9375, 28178, 450775, 9780504, 1795265022}) {
1325 uint64_t x = _detail::expo_mod(a, d, n);
1326 if (x == 1
or x == n - 1
or a % n == 0)
1329 for (uint64_t j = 0; j < r - 1; ++j) {
1330 x = _detail::mul_mod(x, x, n);
1342inline uint64_t pollard_rho(uint64_t n) {
1345 auto f = [n](uint64_t x) {
return mul_mod(x, x, n) + 1; };
1347 uint64_t x = 0, y = 0, t = 30, prd = 2, x0 = 1, q;
1348 while (t % 40 != 0
or std::gcd(prd, n) == 1) {
1351 q = mul_mod(prd, x > y ? x - y : y - x, n);
1354 x = f(x), y = f(f(y)), t++;
1356 return std::gcd(prd, n);
1359inline std::vector<uint64_t> factor(uint64_t n) {
1364 uint64_t d = _detail::pollard_rho(n);
1365 std::vector<uint64_t> l = factor(d), r = factor(n / d);
1366 l.insert(l.end(), r.begin(), r.end());
1376 tgen_ensure(n > 0,
"number to factor must be positive");
1377 auto factors = _detail::factor(n);
1378 std::sort(factors.begin(), factors.end());
1386 tgen_ensure(n > 0,
"number to factor must be positive");
1387 std::vector<std::pair<uint64_t,
int>> primes;
1388 for (uint64_t p : factor(n)) {
1389 if (!primes.empty()
and primes.back().first == p)
1390 ++primes.back().second;
1392 primes.emplace_back(p, 1);
1402inline __int128 modular_inverse_128(
__int128 a,
__int128 mod) {
1404 "remainder must be positive and smaller than the mod");
1406 __int128 t = 0, new_t = 1;
1407 __int128 r = mod, new_r = a;
1409 while (new_r != 0) {
1410 __int128 q = r / new_r;
1412 auto tmp_t = t - q * new_t;
1416 auto tmp_r = r - q * new_r;
1421 tgen_ensure(r == 1,
"remainder and mod must be coprime");
1434 return _detail::modular_inverse_128(a, mod);
1443 for (
auto [p, e] : factor_by_prime(n))
1450inline const std::pair<std::vector<uint64_t>, std::vector<uint64_t>> &
1453 static const std::pair<std::vector<uint64_t>, std::vector<uint64_t>> value{
1455 2, 3, 7, 23, 89, 113, 523, 887, 1129, 1327, 9551, 15683, 19609,
1456 31397, 155921, 360653, 370261, 492113, 1349533, 1357201, 2010733,
1457 4652353, 17051707, 20831323, 47326693, 122164747, 189695659,
1458 191912783, 387096133, 436273009, 1294268491, 1453168141,
1459 2300942549, 3842610773, 4302407359, 10726904659, 20678048297,
1460 22367084959, 25056082087, 42652618343, 127976334671, 182226896239,
1461 241160624143, 297501075799, 303371455241, 304599508537,
1462 416608695821, 461690510011, 614487453523, 738832927927,
1463 1346294310749, 1408695493609, 1968188556461, 2614941710599,
1464 7177162611713, 13829048559701, 19581334192423, 42842283925351,
1465 90874329411493, 171231342420521, 218209405436543, 1189459969825483,
1466 1686994940955803, 1693182318746371, 43841547845541059,
1467 55350776431903243, 80873624627234849, 203986478517455989,
1468 218034721194214273, 305405826521087869, 352521223451364323,
1469 401429925999153707, 418032645936712127, 804212830686677669,
1470 1425172824437699411, 5733241593241196731, 6787988999657777797
1472 {1, 2, 4, 6, 8, 14, 18, 20, 22, 34, 36,
1473 44, 52, 72, 86, 96, 112, 114, 118, 132, 148, 154,
1474 180, 210, 220, 222, 234, 248, 250, 282, 288, 292, 320,
1475 336, 354, 382, 384, 394, 456, 464, 468, 474, 486, 490,
1476 500, 514, 516, 532, 534, 540, 582, 588, 602, 652, 674,
1477 716, 766, 778, 804, 806, 906, 916, 924, 1132, 1184, 1198,
1478 1220, 1224, 1248, 1272, 1328, 1356, 1370, 1442, 1476, 1488, 1510}};
1487 throw tgen::_detail::there_is_no_upto_error(
"prime gap", r);
1489 const auto &[P, G] = prime_gaps();
1490 for (
int i = P.size() - 1;; --i) {
1494 uint64_t right = std::min(r, P[i] + G[i] - 1);
1495 uint64_t prev = i > 0 ? G[i - 1] : 0;
1496 uint64_t curr = right - P[i];
1499 return {P[i] + 1, right};
1506 static const std::vector<uint64_t> highly_composites = {
1507 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680,
1508 2520, 5040, 7560, 10080, 15120, 20160, 25200, 27720, 45360, 50400, 55440,
1509 83160, 110880, 166320, 221760, 277200, 332640, 498960, 554400, 665280,
1510 720720, 1081080, 1441440, 2162160, 2882880, 3603600, 4324320, 6486480,
1511 7207200, 8648640, 10810800, 14414400, 17297280, 21621600, 32432400,
1512 36756720, 43243200, 61261200, 73513440, 110270160, 122522400, 147026880,
1513 183783600, 245044800, 294053760, 367567200, 551350800, 698377680, 735134400,
1514 1102701600, 1396755360, 2095133040, 2205403200, 2327925600, 2793510720,
1515 3491888400, 4655851200, 5587021440, 6983776800, 10475665200, 13967553600,
1516 20951330400, 27935107200, 41902660800, 48886437600, 64250746560,
1517 73329656400, 80313433200, 97772875200, 128501493120, 146659312800,
1518 160626866400, 240940299600, 293318625600, 321253732800, 481880599200,
1519 642507465600, 963761198400, 1124388064800, 1606268664000, 1686582097200,
1520 1927522396800, 2248776129600, 3212537328000, 3373164194400, 4497552259200,
1521 6746328388800, 8995104518400, 9316358251200, 13492656777600, 18632716502400,
1522 26985313555200, 27949074753600, 32607253879200, 46581791256000,
1523 48910880818800, 55898149507200, 65214507758400, 93163582512000,
1524 97821761637600, 130429015516800, 195643523275200, 260858031033600,
1525 288807105787200, 391287046550400, 577614211574400, 782574093100800,
1526 866421317361600, 1010824870255200, 1444035528936000, 1516237305382800,
1527 1732842634723200, 2021649740510400, 2888071057872000, 3032474610765600,
1528 4043299481020800, 6064949221531200, 8086598962041600, 10108248702552000,
1529 12129898443062400, 18194847664593600, 20216497405104000, 24259796886124800,
1530 30324746107656000, 36389695329187200, 48519593772249600, 60649492215312000,
1531 72779390658374400, 74801040398884800, 106858629141264000,
1532 112201560598327200, 149602080797769600, 224403121196654400,
1533 299204161595539200, 374005201994424000, 448806242393308800,
1534 673209363589963200, 748010403988848000, 897612484786617600,
1535 1122015605983272000, 1346418727179926400, 1795224969573235200,
1536 2244031211966544000, 2692837454359852800, 3066842656354276800,
1537 4381203794791824000, 4488062423933088000, 6133685312708553600,
1538 8976124847866176000, 9200527969062830400, 12267370625417107200ULL,
1539 15334213281771384000ULL, 18401055938125660800ULL};
1540 return highly_composites;
1545 for (
int i = highly_composites().size() - 1; i >= 0; --i)
1546 if (highly_composites()[i] <= r)
1547 return highly_composites()[i];
1549 throw tgen::_detail::there_is_no_upto_error(
"highly composite number", r);
1556 throw tgen::_detail::there_is_no_in_range_error(
"prime", l, r);
1557 l = std::max<uint64_t>(l, 2);
1559 if (r - l <= prime_gaps().second.back()) {
1560 std::vector<uint64_t> vals(r - l + 1);
1561 iota(vals.begin(), vals.end(), l);
1562 shuffle(vals.begin(), vals.end());
1563 for (uint64_t i : vals)
1566 throw tgen::_detail::there_is_no_in_range_error(
"prime", l, r);
1579 tgen_ensure(l <= std::numeric_limits<uint64_t>::max() - 58,
1581 for (uint64_t i = std::max<uint64_t>(2, l);; ++i)
1589 for (uint64_t i = r; i >= 2; --i)
1592 throw tgen::_detail::there_is_no_upto_error(
"prime", r);
1596inline bool mul_leq(uint64_t a, uint64_t b, uint64_t limit) {
1599 return a <= limit / b;
1603inline std::optional<uint64_t> expo(uint64_t base, uint64_t exp,
1605 uint64_t result = 1;
1609 if (!mul_leq(result, base, limit))
1610 return std::nullopt;
1619 if (!mul_leq(base, base, limit))
1620 return std::nullopt;
1629inline uint64_t kth_root_floor(uint64_t n, uint64_t k) {
1630 tgen_ensure(k > 0
and n >= 0,
"values must be valid");
1631 if (k == 1
or n <= 1)
1634 uint64_t lo = 1, hi = 1ULL << ((64 + k - 1) / k);
1637 uint64_t mid = lo + (hi - lo + 1) / 2;
1639 if (expo(mid, k, n)) {
1652 for (
auto [p, e] : factor_by_prime(n))
1653 divisors *= (e + 1);
1661 "divisor count must be prime");
1662 int root = divisor_count - 1;
1663 uint64_t p =
gen_prime(kth_root_floor(l, root)
, kth_root_floor(r, root)
);
1664 return *expo(p, root, r);
1671inline __int128 gcd128(
__int128 a,
__int128 b) {
1687inline __int128 mul_saturate(
__int128 a,
__int128 b) {
1689 static const __int128 LIMIT = (
__int128)1 << 64;
1690 if (a == 0
or b == 0)
1701 crt() : a(0), m(1) {}
1702 crt(T a_, T m_) : a(a_), m(m_) {}
1704 if (m == 0
or C.m == 0)
1707 T g = gcd128(m, C.m);
1708 if ((C.a - a) % g != 0)
1717 T inv = modular_inverse_128(m1 % m2, m2);
1719 T k = ((C.a - a) / g) % m2;
1723 k =
static_cast<
unsigned __int128>(k) * inv % m2;
1725 T lcm = mul_saturate(m, m2);
1727 T res = (a +
static_cast<T>((
static_cast<
unsigned __int128>(k) * m) %
1743 std::vector<uint64_t> rems,
1744 std::vector<uint64_t> mods) {
1746 throw tgen::_detail::there_is_no_in_range_error(
"congruent number", l,
1749 "number of remainders and mods must be the same");
1752 for (
int i = 0; i <
static_cast<
int>(rems.size()); ++i) {
1754 "remainder must be smaller than the mod");
1755 crt = crt * _detail::
crt(rems[i], mods[i]);
1757 if (crt.a == -1
or crt.m > r) {
1758 if (!(l <= crt.a
and crt.a <= r))
1759 throw tgen::_detail::there_is_no_in_range_error(
1760 "congruent number", l, r);
1762 bool valid_candidate =
true;
1763 for (
int j = 0; j <
static_cast<
int>(rems.size()); ++j)
1764 if (crt.a % mods[j] != rems[j])
1765 valid_candidate =
false;
1766 if (valid_candidate)
1768 throw tgen::_detail::there_is_no_in_range_error(
"congruent number",
1773 uint64_t k_min = crt.a >= l ? 0 : ((l - crt.a) + crt.m - 1) / crt.m;
1774 uint64_t k_max = (r - crt.a) / crt.m;
1777 throw tgen::_detail::there_is_no_in_range_error(
"congruent number", l,
1780 return crt.a + next(k_min, k_max) * crt.m;
1787 return gen_congruent(l, r, std::vector<uint64_t>({rem}),
1788 std::vector<uint64_t>({mod}));
1806 static const std::vector<uint64_t> fib = [] {
1807 std::vector<uint64_t> v = {0, 1};
1809 std::numeric_limits<uint64_t>::max() - v[v.size() - 2])
1810 v.push_back(v.back() + v[v.size() - 2]);
1818inline constexpr long double LOG_ZERO = -INFINITY;
1819inline constexpr long double LOG_ONE = 0.0;
1821inline long double log_space(
long double x) {
1822 return x == 0.0 ? LOG_ZERO : std::log(x);
1826inline long double add_log_space(
long double a,
long double b) {
1835 return a + log1p(exp(b - a));
1840inline long double sub_log_space(
long double a,
long double b) {
1845 return a + log1p(-exp(b - a));
1857 part_r = std::min(part_r, n);
1858 tgen_ensure(n > 0
and part_l > 0,
"invalid parameters to gen_partition");
1859 tgen_ensure(part_l <= n
and part_r > 0,
"no such partition");
1862 std::vector<
long double> dp(n + 1, _detail::LOG_ZERO);
1863 dp[0] = _detail::LOG_ONE;
1864 long double window = _detail::LOG_ZERO;
1865 for (
int i = 1; i <= n; ++i) {
1867 window = _detail::add_log_space(window, dp[i - part_l]);
1868 if (i >= part_r + 1)
1869 window = _detail::sub_log_space(window, dp[i - part_r - 1]);
1876 for (
int i = 1; i <= n; ++i)
1877 dp_pref[i] = _detail::add_log_space(dp_pref[i - 1], dp[i]);
1879 std::vector<
int> part;
1883 int l = std::max(0, sum - part_r), r = sum - part_l;
1884 tgen::_detail::tgen_ensure_against_bug(r >= 0);
1886 int nxt_sum = std::min(sum, r);
1887 long double random = next<
long double>(0, 1);
1898 long double val_l = l ? dp_pref[l - 1] : _detail::LOG_ZERO,
1900 while (nxt_sum > l
and
1901 dp_pref[nxt_sum - 1] >=
1902 val_r + _detail::log_space(random + (1 - random) *
1903 exp(val_l - val_r)))
1906 part.push_back(sum - nxt_sum);
1921 part_r = std::min(part_r, n);
1923 "invalid parameters to gen_partition_fixed_size");
1924 tgen_ensure(
static_cast<
long long>(k) * part_l <= n
and
1925 n <=
static_cast<
long long>(k) * part_r,
1926 "no such partition");
1929 int s = n - k * part_l;
1931 std::vector<
int> part(k);
1934 std::vector<
int> cuts = {-1};
1936 int total = s + k - 1, bars = k - 1;
1937 for (
int i = 0; i < total
and bars > 0; ++i)
1938 if (next<
long double>(0, 1) <
1939 static_cast<
long double>(bars) / (total - i)) {
1943 cuts.push_back(total);
1946 for (
int i = 0; i < k; ++i)
1947 part[i] = cuts[i + 1] - cuts[i] - 1;
1950 int u = part_r - part_l;
1953 std::vector<std::vector<
long double>> dp(
1954 k + 1, std::vector<
long double>(s + 1, _detail::LOG_ZERO));
1955 dp[0][0] = _detail::LOG_ONE;
1957 for (
int i = 1; i <= k; ++i) {
1958 std::vector<
long double> pref = dp[i - 1];
1959 for (
int j = 1; j <= s; ++j)
1960 pref[j] = _detail::add_log_space(pref[j - 1], dp[i - 1][j]);
1962 for (
int j = 0; j <= s; ++j) {
1966 _detail::sub_log_space(dp[i][j], pref[j - u - 1]);
1971 int left_to_distribute = s;
1972 for (
int i = k; i >= 1; --i) {
1973 long double log_total = _detail::LOG_ZERO;
1974 for (
int j = 0; j <= u
and j <= left_to_distribute; ++j)
1975 log_total = _detail::add_log_space(
1976 log_total, dp[i - 1][left_to_distribute - j]);
1977 tgen::_detail::tgen_ensure_against_bug(log_total !=
1984 long double random =
1985 _detail::log_space(next<
long double>(0, 1)) + log_total;
1987 long double cur_prob = _detail::LOG_ZERO;
1989 for (
int j = 0; j <= u
and j <= left_to_distribute; ++j) {
1990 cur_prob = _detail::add_log_space(
1991 cur_prob, dp[i - 1][left_to_distribute - j]);
1992 if (random < cur_prob) {
1998 part[k - i] = chosen;
1999 left_to_distribute -= chosen;
C::value_type any(const C &container)
Choses a random element from container.
C shuffled(const C &container)
Shuffles a container.
void shuffle(It first, It last)
Shuffles range inplace, for random_access_iterator.
It::value_type any(It first, It last)
Choses a random element from iterator range.
T next(T l, T r)
Returns a random number in [l, r].
#define tgen_ensure(cond,...)
Ensures condition is true.
C choose(int k, const C &container)
Chooses elements from container, as in a subsequence fixed length.
std::pair< uint64_t, uint64_t > prime_gap_upto(uint64_t r)
Largest prime gap up to given number.
uint64_t gen_odd(uint64_t l, uint64_t r)
Generates random odd number in a given range.
uint64_t prime_upto(uint64_t r)
Computes largest prime up to given value.
std::vector< int > gen_partition(int n, int part_l=1, int part_r=-1)
Generates a random partition of a number.
std::vector< int > gen_partition_fixed_size(int n, int k, int part_l=0, int part_r=-1)
Generates a random partition with fixed size of a number.
uint64_t totient(uint64_t n)
Euler's totient function.
uint64_t prime_from(uint64_t l)
Computes smallest prime from given value.
std::vector< uint64_t > factor(uint64_t n)
Factors a number into primes.
int num_divisors(uint64_t n)
Computes the number of divisors of a given number.
bool is_prime(uint64_t n)
Checks if a number is prime.
uint64_t gen_prime(uint64_t l, uint64_t r)
Generates a random prime in given range.
constexpr int FFT_MOD
FFT/NTT mod.
uint64_t gen_congruent(uint64_t l, uint64_t r, uint64_t rem, uint64_t mod)
Generates random number in range given a modular congruence.
uint64_t gen_congruent(uint64_t l, uint64_t r, std::vector< uint64_t > rems, std::vector< uint64_t > mods)
Generates random number in range given modular congruences.
uint64_t gen_even(uint64_t l, uint64_t r)
Generates random even number in a given range.
uint64_t highly_composite_upto(uint64_t r)
Largest highly composite number up to given number.
std::vector< std::pair< uint64_t, int > > factor_by_prime(uint64_t n)
Factors a number into primes and its powers.
const std::vector< uint64_t > & fibonacci()
Fetches Fibonacci numbers.
uint64_t modular_inverse(uint64_t a, uint64_t mod)
Computes modular inverse.
uint64_t gen_divisor_count(uint64_t l, uint64_t r, int divisor_count)
Generates random number in range with a given prime number of divisors.
const std::vector< uint64_t > & highly_composites()
Fetches highly composite numbers.
T opt(const Key &key, std::optional< T > default_value=std::nullopt)
Gets opt by key.
bool has_opt(std::size_t index)
Checks if opt at some index exists.
bool has_opt(const std::string &key)
Checks if opt with with some key exists.
void register_gen(int argc, char **argv)
Sets up the generator.
instance gen() const
Generates a random instance from the set of valid permutations.
permutation & set(int idx, int value)
Restricts generator s.t. value at index is fixed.
permutation(int size)
Creates permutation generator defined by size.
instance gen(std::vector< int > cycle_sizes) const
Generates a random instance from the set of valid permutations, given a list of cycle sizes.
instance(const std::vector< int > &vec)
Creates a permutation instance from a std::vector.
int & operator[](int idx)
Returns the value at some position of the instance.
std::vector< int > to_std() const
Converts the instance to a std::vector.
int size() const
Returns the size of the permutation instance.
instance & reverse()
Reverses the instance.
instance & add_1()
Adds 1 for printing.
instance & sort()
Sorts the instance in non-decreasing order.
instance & inverse()
Inverse of the permutation.
int parity() const
Parity of the permutation.
sequence(int size, std::set< T > values)
Creates sequence generator define by value set.
sequence & distinct(std::set< int > indices)
Restricts generator s.t. all values at index set are distinct.
sequence & different(int idx_1, int idx_2)
Restricts generator s.t. values at two indices are different.
sequence & distinct()
Restricts generator s.t. all values are distinct.
instance gen() const
Generates a random instance from the set of valid sequences.
sequence & equal_range(int left, int right)
Restricts generator s.t. all values at index range are the same.
sequence & equal(int idx_1, int idx_2)
Restricts generator s.t. values at two indices are the same.
sequence & set(int idx, T value)
Restricts generator s.t. value at index is fixed.
sequence(int size, T value_l, T value_r)
Creates sequence generator define by size and range of values.
instance & reverse()
Reverses the instance.
instance operator+(const instance &rhs)
Concatenates two instances.
instance(const std::vector< T > &vec)
Creates a sequence instance from a std::vector.
const T & operator[](int idx) const
Returns the value at some position of the instance.
int size() const
Returns the size of the sequence instance.
instance & sort()
Sorts the instance in non-decreasing order.
std::vector< T > to_std() const
Converts the instance to a std::vector.
Printer helper for standard types.