// fken_cpl: https://github.com/fken57/strong_cp_lang // Converter source: https://github.com/fken57/strong_cp_lang/tree/deploy/neoshowcase // Original fken source: // deque dq; // ll N; // cin >> N; // vector A(N); // cin >> A; // dq.push_back(-1); // dq.push_back(-2); // dq.push_back(-3); // ll ans=0; // rep(i,0,N){ // dq.push_back(A[i]); // ll x=dq.size(); // if(dq[x-1]==dq[x-2] && dq[x-2]==dq[x-3]){ // ans+=3; // rep(j,0,3) dq.pop_back(); // } // } // // print(ans); // End original fken source. // Generated by fken_cpl. Compile with GCC/Clang C++20 and Boost headers. #ifndef FKEN_RUNTIME_HPP #define FKEN_RUNTIME_HPP #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace fken { inline double finite_double(double value) { if (!std::isfinite(value)) throw std::domain_error("double result must be finite"); return value; } class Int { using Big = boost::multiprecision::cpp_int; enum class Infinity { negative = -1, positive = 1 }; std::variant value_; static constexpr auto min = std::numeric_limits::min(); static constexpr auto max = std::numeric_limits::max(); friend Int bit_width(const Int &value); friend Int popcount(const Int &value); Big big() const { if (const auto *v = std::get_if(&value_)) return Big(*v); return std::get(value_); } explicit Int(Big value) { if (value >= min && value <= max) value_ = value.convert_to(); else value_ = std::move(value); } explicit Int(Infinity value) : value_(value) {} int infinity_sign() const { const auto *value = std::get_if(&value_); return value ? static_cast(*value) : 0; } static int compare(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) { return a.infinity_sign() - b.infinity_sign(); } if (!a.is_big() && !b.is_big()) { auto x = std::get(a.value_); auto y = std::get(b.value_); return (x > y) - (x < y); } return a.big().compare(b.big()); } public: Int(std::int64_t value = 0) : value_(value) {} static Int infinity() { return Int(Infinity::positive); } static Int from_double(double value) { return Int(Big(finite_double(value))); } bool is_finite() const { return !std::holds_alternative(value_); } static Int parse(std::string_view text) { if (text == "INF" || text == "inf") return infinity(); if (text == "-INF" || text == "-inf") return -infinity(); std::int64_t small = 0; const auto result = std::from_chars(text.data(), text.data() + text.size(), small); if (result.ec == std::errc{} && result.ptr == text.data() + text.size()) { return Int(small); } bool negative = !text.empty() && text.front() == '-'; if (negative || (!text.empty() && text.front() == '+')) text.remove_prefix(1); if (text.empty()) throw std::invalid_argument("invalid integer"); Big value = 0; for (char c : text) { if (c < '0' || c > '9') throw std::invalid_argument("invalid integer"); value *= 10; value += c - '0'; } if (negative) value = -value; return Int(std::move(value)); } std::size_t hash() const { if (!is_finite()) return std::hash{}(infinity_sign()); if (is_big()) return boost::multiprecision::hash_value(std::get(value_)); return std::hash{}(std::get(value_)); } bool is_big() const { return std::holds_alternative(value_); } std::int64_t to_int64() const { if (!is_finite() || is_big()) throw std::out_of_range("int64 conversion is out of range"); return std::get(value_); } double to_double() const { if (!is_finite()) throw std::domain_error("double conversion requires a finite integer"); if (!is_big()) return static_cast(std::get(value_)); const auto decimal = std::get(value_).str(); return finite_double(std::strtod(decimal.c_str(), nullptr)); } std::size_t to_size(const char *context) const { if (!is_finite() || is_big()) throw std::out_of_range(std::string(context) + " is out of range"); auto value = std::get(value_); if (value < 0 || static_cast(value) > std::numeric_limits::max()) { throw std::out_of_range(std::string(context) + " is out of range"); } return static_cast(value); } explicit operator bool() const { if (!is_finite()) return true; if (!is_big()) return std::get(value_) != 0; return std::get(value_) != 0; } friend Int operator+(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) { if (a.infinity_sign() * b.infinity_sign() < 0) throw std::domain_error("opposite infinities cannot be added"); return a.is_finite() ? b : a; } if (!a.is_big() && !b.is_big()) { std::int64_t result; if (!__builtin_add_overflow(std::get(a.value_), std::get(b.value_), &result)) { return Int(result); } } return Int(Big(a.big() + b.big())); } friend Int operator-(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) { if (a.infinity_sign() * b.infinity_sign() > 0) throw std::domain_error("equal infinities cannot be subtracted"); return a.is_finite() ? -b : a; } if (!a.is_big() && !b.is_big()) { std::int64_t result; if (!__builtin_sub_overflow(std::get(a.value_), std::get(b.value_), &result)) { return Int(result); } } return Int(Big(a.big() - b.big())); } friend Int operator*(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) { const int sign = compare(a, Int(0)) * compare(b, Int(0)); if (!sign) throw std::domain_error("zero cannot be multiplied by infinity"); return sign < 0 ? -infinity() : infinity(); } if (!a.is_big() && !b.is_big()) { std::int64_t result; if (!__builtin_mul_overflow(std::get(a.value_), std::get(b.value_), &result)) { return Int(result); } } return Int(Big(a.big() * b.big())); } friend Int operator/(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("division requires finite operands"); if (!static_cast(b)) throw std::domain_error("division by zero"); if (!a.is_big() && !b.is_big()) { auto x = std::get(a.value_); auto y = std::get(b.value_); if (!(x == min && y == -1)) return Int(x / y); } return Int(Big(a.big() / b.big())); } friend Int operator%(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("remainder requires finite operands"); if (!b) throw std::domain_error("division by zero"); if (!a.is_big() && !b.is_big()) { auto x = std::get(a.value_); auto y = std::get(b.value_); return Int(y == -1 ? 0 : x % y); } return Int(Big(a.big() % b.big())); } friend Int operator-(const Int &a) { if (!a.is_finite()) return Int(a.infinity_sign() < 0 ? Infinity::positive : Infinity::negative); if (!a.is_big()) { auto x = std::get(a.value_); if (x != min) return Int(-x); } return Int(Big(-a.big())); } friend Int operator~(const Int &value) { if (!value.is_finite()) throw std::domain_error("bit complement requires a finite operand"); // Infinite two's-complement sign extension gives ~x == -1 - x. return Int(-1) - value; } friend Int operator&(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("bit operations require finite operands"); if (!a.is_big() && !b.is_big()) return Int(std::get(a.value_) & std::get(b.value_)); return Int(Big(a.big() & b.big())); } friend Int operator|(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("bit operations require finite operands"); if (!a.is_big() && !b.is_big()) return Int(std::get(a.value_) | std::get(b.value_)); return Int(Big(a.big() | b.big())); } friend Int operator^(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("bit operations require finite operands"); if (!a.is_big() && !b.is_big()) return Int(std::get(a.value_) ^ std::get(b.value_)); return Int(Big(a.big() ^ b.big())); } friend Int operator<<(const Int &value, const Int &count) { if (!value.is_finite() || !count.is_finite() || count < Int(0)) throw std::domain_error("shift requires a finite value and finite nonnegative count"); if (!value || !count) return value; Big result = value.big(); const Big magnitude = result < 0 ? -result : result; const auto bit_width = std::uint64_t(boost::multiprecision::msb(magnitude)) + 1; // Keep the final bit length representable by the multiprecision backend. const Int available = Int(std::numeric_limits::max()) - Int(static_cast(bit_width)); if (count > available) throw std::overflow_error("integer shift result is too large"); result <<= count.to_size("shift count"); return Int(std::move(result)); } friend Int operator>>(const Int &value, const Int &count) { if (!value.is_finite() || !count.is_finite() || count < Int(0)) throw std::domain_error("shift requires a finite value and finite nonnegative count"); if (!value || !count) return value; if (!value.is_big()) { const auto small = std::get(value.value_); if (count >= Int(64)) return Int(small < 0 ? -1 : 0); return Int(small >> count.to_size("shift count")); } const bool negative = static_cast(value < Int(0)); Big bits = value.big(); // Shift the complement when negative to preserve infinite sign extension. if (negative) bits = -bits - 1; if (count > Int(boost::multiprecision::msb(bits))) return Int(negative ? -1 : 0); bits >>= count.to_size("shift count"); if (negative) bits = -bits - 1; return Int(std::move(bits)); } friend Int operator==(const Int &a, const Int &b) { return Int(compare(a, b) == 0); } friend Int operator!=(const Int &a, const Int &b) { return Int(compare(a, b) != 0); } friend Int operator<(const Int &a, const Int &b) { return Int(compare(a, b) < 0); } friend Int operator<=(const Int &a, const Int &b) { return Int(compare(a, b) <= 0); } friend Int operator>(const Int &a, const Int &b) { return Int(compare(a, b) > 0); } friend Int operator>=(const Int &a, const Int &b) { return Int(compare(a, b) >= 0); } Int &operator+=(const Int &other) { *this = *this + other; return *this; } Int &operator-=(const Int &other) { *this = *this - other; return *this; } Int &operator*=(const Int &other) { *this = *this * other; return *this; } Int &operator%=(const Int &other) { *this = *this % other; return *this; } Int &operator/=(const Int &other) { *this = *this / other; return *this; } friend std::ostream &operator<<(std::ostream &out, const Int &value) { if (!value.is_finite()) return out << (value.infinity_sign() < 0 ? "-INF" : "INF"); if (!value.is_big()) return out << std::get(value.value_); return out << std::get(value.value_); } }; inline void set_precision(std::ostream &out, const Int &value) { auto precision = value.to_size("output precision"); if (precision > 100) throw std::out_of_range("output precision must be between 0 and 100"); out.precision(static_cast(precision)); } inline void assert_condition(const Int &condition, const std::string &message) { if (!condition) throw std::domain_error(message.empty() ? "assertion failed" : message); } template bool fits_width(const Int &value) { static_assert(Bits == 32 || Bits == 64); if (!value.is_finite() || value.is_big()) return false; if constexpr (Bits == 64) return true; return value >= Int(std::numeric_limits::min()) && value <= Int(std::numeric_limits::max()); } template Int narrow_integer(Int value) { if (!fits_width(value)) { throw std::out_of_range(Bits == 32 ? "int32 conversion is out of range" : "int64 conversion is out of range"); } return value; } template Int checked_width(Int value) { if constexpr (Bits != 0) { if (!fits_width(value)) throw std::overflow_error("fixed-width integer overflow"); } return value; } template void check_shift_count(const Int &count) { if constexpr (Bits != 0) { if (count < Int(0) || count >= Int(Bits)) throw std::domain_error("shift count is out of range for the fixed width"); } } template Int shift_left(const Int &value, const Int &count) { check_shift_count(count); Int result = value << count; if constexpr (Bits != 0) { const Int modulus = Int(1) << Int(Bits); result = result & (modulus - Int(1)); if (result >= (modulus >> Int(1))) result -= modulus; } return result; } template Int shift_right(const Int &value, const Int &count) { check_shift_count(count); return value >> count; } inline Int min(const Int &a, const Int &b) { return a <= b ? a : b; } inline Int max(const Int &a, const Int &b) { return a >= b ? a : b; } inline Int rep_boundary(Int value) { if (!value.is_finite()) throw std::domain_error("rep boundary must be finite"); return value; } template Int power(Int base, Int exponent) { if (!base.is_finite() || !exponent.is_finite()) throw std::domain_error("power requires finite operands"); if (exponent < Int(0)) throw std::domain_error("negative integer exponent"); if (!exponent) return Int(1); if (base == Int(0) || base == Int(1)) return base; if (base == Int(-1)) return exponent % Int(2) ? Int(-1) : Int(1); Int result(1); while (exponent) { if (exponent % Int(2)) result = checked_width(result * base); exponent /= Int(2); if (exponent) base = checked_width(base * base); } return result; } template class Bitset { std::bitset bits_; public: Int size() const { return Int(static_cast(N)); } Int count() const { return Int(static_cast(bits_.count())); } Int all() const { return Int(bits_.all()); } Int any() const { return Int(bits_.any()); } Int none() const { return Int(bits_.none()); } Int test(const Int &index) const { return Int(bits_.test(index.to_size("bit index"))); } void set() { bits_.set(); } void set(const Int &index, const Int &value = Int(1)) { bits_.set(index.to_size("bit index"), static_cast(value)); } void reset() { bits_.reset(); } void reset(const Int &index) { bits_.reset(index.to_size("bit index")); } void flip() { bits_.flip(); } void flip(const Int &index) { bits_.flip(index.to_size("bit index")); } }; template Int at(const Bitset &bits, const Int &index) { return bits.test(index); } inline Int abs(const Int &value) { return value < Int(0) ? -value : value; } inline double abs(double value) { return std::abs(value); } inline double sqrt(double value) { if (value < 0) throw std::domain_error("sqrt requires a nonnegative argument"); return std::sqrt(value); } inline double log2(double value) { if (value <= 0) throw std::domain_error("log2 requires a positive argument"); return std::log2(value); } inline Int pow(Int base, Int exponent) { return power(std::move(base), std::move(exponent)); } inline double pow(double base, double exponent) { return finite_double(std::pow(base, exponent)); } template T clamp(const T &value, const T &lower, const T &upper) { if (lower > upper) throw std::domain_error("clamp lower bound exceeds upper bound"); return value < lower ? lower : value > upper ? upper : value; } inline Int rounded_division(const Int &a, const Int &b, bool round_up) { const Int quotient = a / b; if (!(a % b)) return quotient; const bool same_sign = static_cast(a < Int(0)) == static_cast(b < Int(0)); if (same_sign != round_up) return quotient; return quotient + Int(round_up ? 1 : -1); } inline Int floor_div(const Int &a, const Int &b) { return rounded_division(a, b, false); } inline Int ceil_div(const Int &a, const Int &b) { return rounded_division(a, b, true); } inline void require_nonnegative_integer(const Int &value, const char *name) { if (!value.is_finite() || value < Int(0)) throw std::domain_error(std::string(name) + " requires a finite nonnegative integer"); } inline Int bit_width(const Int &value) { require_nonnegative_integer(value, "bit_width"); if (!value.is_big()) return Int(std::bit_width(static_cast(value.to_int64()))); return Int(static_cast(boost::multiprecision::msb(std::get(value.value_))) + 1); } inline Int isqrt(const Int &value) { require_nonnegative_integer(value, "isqrt"); if (value < Int(2)) return value; Int bound = Int(1) << ((bit_width(value) + Int(1)) / Int(2)); for (;;) { Int next = (bound + value / bound) >> Int(1); if (next >= bound) return bound; bound = std::move(next); } } inline Int popcount(const Int &value) { require_nonnegative_integer(value, "popcount"); if (!value.is_big()) return Int(std::popcount(static_cast(value.to_int64()))); std::vector words; boost::multiprecision::export_bits(std::get(value.value_), std::back_inserter(words), 64, false); std::int64_t count = 0; for (auto word : words) count += std::popcount(word); return Int(count); } inline Int bit_floor(const Int &value) { require_nonnegative_integer(value, "bit_floor"); return value ? Int(1) << (bit_width(value) - Int(1)) : Int(0); } inline Int bit_ceil(const Int &value) { require_nonnegative_integer(value, "bit_ceil"); return value <= Int(1) ? Int(1) : Int(1) << bit_width(value - Int(1)); } inline Int has_single_bit(const Int &value) { require_nonnegative_integer(value, "has_single_bit"); return Int(value && !(value & (value - Int(1)))); } inline void require_bit_index(const Int &value, const Int &index) { if (!value.is_finite() || !index.is_finite() || index < Int(0)) throw std::domain_error("bit access requires a finite integer and a finite nonnegative index"); } inline Int get_bit(const Int &value, const Int &index) { require_bit_index(value, index); return (value >> index) & Int(1); } inline Int set_bit(const Int &value, const Int &index) { return get_bit(value, index) ? value : value | (Int(1) << index); } inline Int clear_bit(const Int &value, const Int &index) { return get_bit(value, index) ? value & ~(Int(1) << index) : value; } inline Int flip_bit(const Int &value, const Int &index) { require_bit_index(value, index); return value ^ (Int(1) << index); } inline Int gcd(Int a, Int b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("gcd requires finite integers"); while (b) { Int remainder = a % b; a = std::move(b); b = std::move(remainder); } return abs(a); } inline Int lcm(const Int &a, const Int &b) { if (!a.is_finite() || !b.is_finite()) throw std::domain_error("lcm requires finite integers"); if (!a || !b) return Int(0); return abs((a / gcd(a, b)) * b); } inline Int normalize_mod(const Int &value, const Int &modulus) { Int remainder = value % modulus; return remainder < Int(0) ? remainder + modulus : remainder; } inline Int mod(const Int &value, const Int &modulus) { if (!modulus.is_finite() || modulus <= Int(0)) throw std::domain_error("mod requires a finite positive modulus"); return normalize_mod(value, modulus); } inline Int pow_mod(Int base, Int exponent, const Int &modulus) { if (modulus <= Int(0) || exponent < Int(0)) throw std::domain_error("pow_mod requires a positive modulus and nonnegative exponent"); base = normalize_mod(base, modulus); Int result = Int(1) % modulus; while (exponent) { if (exponent % Int(2)) result = (result * base) % modulus; exponent /= Int(2); if (exponent) base = (base * base) % modulus; } return result; } inline Int inv_mod(const Int &value, const Int &modulus) { if (modulus <= Int(0)) throw std::domain_error("inv_mod requires a positive modulus"); Int a = modulus, b = normalize_mod(value, modulus), x(0), y(1); while (b) { Int quotient = a / b; Int next = a - quotient * b; a = std::move(b); b = std::move(next); next = x - quotient * y; x = std::move(y); y = std::move(next); } if (a != Int(1)) throw std::domain_error("value and modulus must be coprime"); return normalize_mod(x, modulus); } template class Mint { Int value_; static const Int &modulus() { return Modulus::value(); } public: Mint() = default; explicit Mint(const Int &value) : value_(normalize_mod(value, modulus())) {} const Int &val() const { return value_; } Mint pow(const Int &exponent) const { return Mint(pow_mod(value_, exponent, modulus())); } friend Mint operator+(const Mint &a, const Mint &b) { return Mint(a.value_ + b.value_); } friend Mint operator-(const Mint &a, const Mint &b) { return Mint(a.value_ - b.value_); } friend Mint operator*(const Mint &a, const Mint &b) { return Mint(a.value_ * b.value_); } friend Mint operator/(const Mint &a, const Mint &b) { return Mint(a.value_ * inv_mod(b.value_, modulus())); } friend Mint operator-(const Mint &a) { return Mint(-a.value_); } friend Int operator==(const Mint &a, const Mint &b) { return a.value_ == b.value_; } friend Int operator!=(const Mint &a, const Mint &b) { return a.value_ != b.value_; } Mint &operator+=(const Mint &b) { return *this = *this + b; } Mint &operator-=(const Mint &b) { return *this = *this - b; } Mint &operator*=(const Mint &b) { return *this = *this * b; } Mint &operator/=(const Mint &b) { return *this = *this / b; } friend std::ostream &operator<<(std::ostream &out, const Mint &value) { return out << value.value_; } }; template struct VectorType { using type = std::vector::type>; }; template <> struct VectorType<1, char> { using type = std::string; }; template struct VectorType<0, Element> { using type = Element; }; template using Vec = typename VectorType::type; using Array = Vec<1>; template class SequenceIterator { const Sequence *owner_; std::size_t position_; void require_same_owner(const SequenceIterator &other) const { if (owner_ != other.owner_) throw std::invalid_argument("iterators must refer to the same vector"); } static Int as_int(std::size_t position) { return Int(static_cast(position)); } public: SequenceIterator(const Sequence &owner, std::size_t position) : owner_(&owner), position_(position) {} typename Sequence::value_type operator*() const { if (position_ >= owner_->size()) throw std::out_of_range("cannot dereference the end iterator"); return (*owner_)[position_]; } SequenceIterator operator+(const Int &delta) const { const Int candidate = as_int(position_) + delta; if (!candidate.is_finite() || candidate < Int(0) || candidate > as_int(owner_->size())) throw std::out_of_range("iterator advance is out of range"); return SequenceIterator(*owner_, candidate.to_size("iterator position")); } SequenceIterator operator-(const Int &delta) const { return *this + -delta; } SequenceIterator &operator+=(const Int &delta) { return *this = *this + delta; } SequenceIterator &operator-=(const Int &delta) { return *this = *this - delta; } Int operator-(const SequenceIterator &other) const { require_same_owner(other); return as_int(position_) - as_int(other.position_); } bool operator==(const SequenceIterator &other) const { require_same_owner(other); return position_ == other.position_; } std::strong_ordering operator<=>(const SequenceIterator &other) const { require_same_owner(other); return position_ <=> other.position_; } }; template SequenceIterator begin(const Sequence &owner) { return {owner, 0}; } template SequenceIterator end(const Sequence &owner) { return {owner, owner.size()}; } inline Array divisors(const Int &value) { if (!value.is_finite() || value <= Int(0)) throw std::domain_error("divisors requires a finite positive integer"); Array smaller, larger; const Int limit = isqrt(value); for (Int candidate(1); candidate <= limit; candidate += Int(1)) { if (value % candidate) continue; const Int paired = value / candidate; smaller.push_back(candidate); if (candidate != paired) larger.push_back(paired); } smaller.insert(smaller.end(), std::make_move_iterator(larger.rbegin()), std::make_move_iterator(larger.rend())); return smaller; } struct SubmaskRange { Int mask; struct Iterator { Int mask, current; bool done = false; bool operator!=(std::default_sentinel_t) const { return !done; } Int operator*() const { return current; } void operator++() { if (!current) done = true; else current = (current - Int(1)) & mask; } }; Iterator begin() const { return {mask, mask}; } std::default_sentinel_t end() const { return {}; } }; inline SubmaskRange submasks(const Int &mask) { if (!mask.is_finite() || mask < Int(0)) throw std::domain_error("submasks requires a finite nonnegative integer"); return {mask}; } template struct IndexSelectionRange { using Values = Vec<1, T>; Values input; std::size_t count; struct Iterator { const Values &input; std::vector indices; bool done; bool operator!=(std::default_sentinel_t) const { return !done; } Values operator*() const { Values result; result.reserve(indices.size()); for (std::size_t i : indices) result.push_back(input[i]); return result; } void operator++() { if constexpr (Permute) { done = !std::next_permutation(indices.begin(), indices.end()); } else { const std::size_t gap = input.size() - indices.size(); std::size_t i = indices.size(); while (i && indices[i-1] == gap + i - 1) --i; if (!i) { done = true; return; } ++indices[i-1]; for (; i < indices.size(); ++i) indices[i] = indices[i-1] + 1; } } }; Iterator begin() const { if (count > input.size()) return {input, {}, true}; std::vector indices(count); for (std::size_t i = 0; i < count; ++i) indices[i] = i; return {input, std::move(indices), false}; } std::default_sentinel_t end() const { return {}; } }; template auto combinations(const Sequence &input, const Int &count) { using T = typename Sequence::value_type; if (!count.is_finite() || count < Int(0)) throw std::domain_error("combinations requires a finite nonnegative count"); const auto size = input.size(); const auto length = count <= Int(static_cast(size)) ? count.to_size("combination count") : size + 1; return IndexSelectionRange{Vec<1,T>(input.begin(), input.end()), length}; } template auto permutations(const Sequence &input) { using T = typename Sequence::value_type; return IndexSelectionRange{Vec<1,T>(input.begin(), input.end()), input.size()}; } struct PartitionRange { Int total; struct Iterator { Array parts; bool done = false; bool operator!=(std::default_sentinel_t) const { return !done; } const Array &operator*() const { return parts; } void operator++() { Int remainder; while (!parts.empty() && parts.back() == Int(1)) { parts.pop_back(); remainder += Int(1); } if (parts.empty()) { done = true; return; } const Int largest = parts.back() - Int(1); parts.back() = largest; remainder += Int(1); while (remainder > largest) { parts.push_back(largest); remainder -= largest; } parts.push_back(std::move(remainder)); } }; Iterator begin() const { return {total ? Array{total} : Array{}}; } std::default_sentinel_t end() const { return {}; } }; inline PartitionRange integer_partitions(const Int &total) { if (!total.is_finite() || total < Int(0)) throw std::domain_error("integer_partitions requires a finite nonnegative integer"); return {total}; } template struct EnumerateRange { Vec<1, T> input; struct Iterator { const Vec<1, T> &input; std::size_t position = 0; bool operator!=(std::default_sentinel_t) const { return position < input.size(); } Entry operator*() const { return {Int(static_cast(position)), input[position]}; } void operator++() { ++position; } }; Iterator begin() const { return {input}; } std::default_sentinel_t end() const { return {}; } }; template auto enumerate(const Sequence &input) { using T = typename Sequence::value_type; return EnumerateRange{Vec<1,T>(input.begin(), input.end())}; } template Vec<1, Range> quotient_ranges(const Int &value) { if (!value.is_finite() || value < Int(0)) throw std::domain_error("quotient_ranges requires a finite nonnegative integer"); Vec<1, Range> result; for (Int left(1); left <= value;) { const Int quotient = value / left; Int right = value / quotient + Int(1); result.push_back(Range{std::move(left), right, quotient}); left = std::move(right); } return result; } template struct FixedArray { using value_type = T; std::array values{}; auto begin() { return values.begin(); } auto end() { return values.end(); } auto begin() const { return values.begin(); } auto end() const { return values.end(); } std::size_t size() const { return N; } bool empty() const { return N == 0; } const T &front() const { return values.at(0); } const T &back() const { return values.at(N ? N - 1 : 0); } const T &at(std::size_t index) const { return values.at(index); } const T &operator[](std::size_t index) const { return values[index]; } }; inline void transpose(Vec<2> &values) { if (values.empty()) return; const std::size_t rows = values.size(); const std::size_t columns = values.front().size(); for (const auto &row : values) { if (row.size() != columns) throw std::domain_error("transpose requires a rectangular vector"); } if (columns == 0) { values.clear(); return; } Vec<2> result(columns, Array(rows)); for (std::size_t i = 0; i < rows; ++i) for (std::size_t j = 0; j < columns; ++j) result[j][i] = std::move(values[i][j]); values = std::move(result); } template Array cumulative(const Sequence &values, Int identity, Combine combine) { const auto count = values.size(); Array result(count + 1); if constexpr (Reverse) { result[count] = std::move(identity); for (std::size_t i = count; i > 0; --i) result[i - 1] = combine(values[i - 1], result[i]); } else { result[0] = std::move(identity); for (std::size_t i = 0; i < count; ++i) result[i + 1] = combine(result[i], values[i]); } return result; } template Array prefix_sum(const Sequence &values) { return cumulative(values, Int(0), std::plus{}); } template Array suffix_sum(const Sequence &values) { return cumulative(values, Int(0), std::plus{}); } template Array prefix_min(const Sequence &values) { return cumulative(values, Int::infinity(), fken::min); } template Array suffix_min(const Sequence &values) { return cumulative(values, Int::infinity(), fken::min); } template Array prefix_max(const Sequence &values) { return cumulative(values, -Int::infinity(), fken::max); } template Array suffix_max(const Sequence &values) { return cumulative(values, -Int::infinity(), fken::max); } template Vec<2> prefix_sum_2d(const Matrix &values) { const auto width = values.empty() ? 0 : values.front().size(); for (const auto &row : values) if (row.size() != width) throw std::domain_error("prefix_sum_2d requires a rectangular matrix"); Vec<2> result(values.size() + 1, Array(width + 1)); for (std::size_t i = 0; i < values.size(); ++i) { Int row_sum(0); for (std::size_t j = 0; j < width; ++j) { row_sum += values[i][j]; result[i + 1][j + 1] = result[i][j + 1] + row_sum; } } return result; } inline Array adjacent_difference(const Array &values) { if (values.empty()) return {}; Array result; result.reserve(values.size()); result.push_back(values.front()); for (std::size_t i = 1; i < values.size(); ++i) result.push_back(values[i] - values[i - 1]); return result; } using IntPair = std::pair; inline Int rem(const Int &a, const Int &b) { return a % b; } inline Array divisor_zeta(const Array &values) { Array result = values; for (std::size_t d = 1; d < result.size(); ++d) for (std::size_t m = d + d; m < result.size(); m += d) result[m] += values[d]; return result; } inline Array divisor_mobius(Array values) { for (std::size_t d = 1; d < values.size(); ++d) for (std::size_t m = d + d; m < values.size(); m += d) values[m] -= values[d]; return values; } inline Array multiple_zeta(const Array &values) { Array result = values; for (std::size_t d = 1; d < result.size(); ++d) for (std::size_t m = d + d; m < result.size(); m += d) result[d] += values[m]; return result; } inline Array multiple_mobius(Array values) { for (std::size_t d = values.size(); d > 1;) { --d; for (std::size_t m = d + d; m < values.size(); m += d) values[d] -= values[m]; } return values; } inline Array subset_transform(Array values, bool inverse) { const auto n = values.size(); if (n == 0 || (n & (n - 1))) throw std::domain_error("subset transform requires a power-of-two length"); for (std::size_t bit = 1; bit < n; bit *= 2) for (std::size_t base = 0; base < n; base += 2 * bit) for (std::size_t i = base; i < base + bit; ++i) { if (inverse) values[i + bit] -= values[i]; else values[i + bit] += values[i]; } return values; } inline Array subset_zeta(Array values) { return subset_transform(std::move(values), false); } inline Array subset_mobius(Array values) { return subset_transform(std::move(values), true); } inline bool integer_less(const Int &left, const Int &right) { return static_cast(left < right); } inline constexpr auto ordered_less = [](const auto &lhs, const auto &rhs) { if constexpr (std::is_same_v, char>) return static_cast(lhs) < static_cast(rhs); else if constexpr (std::is_same_v, IntPair>) return lhs.first == rhs.first ? integer_less(lhs.second, rhs.second) : integer_less(lhs.first, rhs.first); else return static_cast(lhs < rhs); }; template auto interval(Sequence &values, const Int &left, const Int &right) { const auto first = left.to_size("interval endpoint"), last = right.to_size("interval endpoint"); if (first > last || last > values.size()) throw std::out_of_range("invalid half-open interval"); return std::pair(values.begin() + first, values.begin() + last); } template void sort(Sequence &values) { std::sort(values.begin(), values.end(), ordered_less); } template void sort(Sequence &values, const Int &left, const Int &right) { const auto [first, last] = interval(values, left, right); std::sort(first, last, ordered_less); } template void rsort(Sequence &values) { std::sort(values.begin(), values.end(), [](const auto &a, const auto &b) { return ordered_less(b, a); }); } template void reverse(Sequence &values) { std::reverse(values.begin(), values.end()); } template void unique(Sequence &values) { auto last = std::unique(values.begin(), values.end(), [](const auto &a, const auto &b) { return static_cast(a == b); }); values.erase(last, values.end()); } inline Int sum(const Array &values) { Int total{}; for (const Int &value : values) total += value; return total; } inline Int sum(const Array &values, const Int &left, const Int &right) { const auto [first, last] = interval(values, left, right); Int total{}; for (auto current = first; current != last; ++current) total += *current; return total; } template Int sum(const Sequence &values, const Function &project) { Int total{}; const auto count = values.size(); for (std::size_t i = 0; i < count; ++i) total += project(values.at(i)); return total; } template Vec<1, T> prefix_fold(const Sequence &values, T first, const Function &combine) { const auto count = values.size(); Vec<1, T> result; result.reserve(count + 1); result.push_back(std::move(first)); for (std::size_t i = 0; i < count; ++i) result.push_back(combine(result.back(), values.at(i))); return result; } template void transform(const Accessor &sequence, const Mapper &map) { const auto count = sequence().size(); for (std::size_t i = 0; i < count; ++i) { auto at = [&]() -> decltype(auto) { auto ¤t = sequence(); if (i >= current.size()) throw std::out_of_range("sequence changed length during transform"); return *(current.begin() + i); }; auto replacement = map(at()); at() = std::move(replacement); } } template Int sequence_predicate(const Accessor &sequence, const Predicate &predicate, bool decisive, bool result) { const auto count = sequence().size(); for (std::size_t i = 0; i < count; ++i) { const auto ¤t = sequence(); if (i >= current.size()) throw std::out_of_range("sequence changed length during predicate evaluation"); if (static_cast(predicate(current.at(i))) == decisive) return Int(result); } return Int(!result); } template Int all_of(const Accessor &sequence, const Predicate &predicate) { return sequence_predicate(sequence, predicate, false, false); } template Int any_of(const Accessor &sequence, const Predicate &predicate) { return sequence_predicate(sequence, predicate, true, true); } template Int none_of(const Accessor &sequence, const Predicate &predicate) { return sequence_predicate(sequence, predicate, true, false); } template Int chmin(T &target, const T &value) { if (!ordered_less(value, target)) return Int(0); target = value; return Int(1); } template Int chmax(T &target, const T &value) { if (!ordered_less(target, value)) return Int(0); target = value; return Int(1); } template Int min_index(const Sequence &values) { if (values.empty()) throw std::domain_error("min requires a nonempty sequence"); return Int(std::min_element(values.begin(), values.end(), ordered_less) - values.begin()); } template Int max_index(const Sequence &values) { if (values.empty()) throw std::domain_error("max requires a nonempty sequence"); return Int(std::max_element(values.begin(), values.end(), ordered_less) - values.begin()); } template typename Sequence::value_type min(const Sequence &values) { return values[min_index(values).to_size("minimum index")]; } template typename Sequence::value_type max(const Sequence &values) { return values[max_index(values).to_size("maximum index")]; } template Int count(const Sequence &values, const typename Sequence::value_type &wanted) { return Int(std::count_if(values.begin(), values.end(), [&](const auto &value) { return static_cast(value == wanted); })); } template Int contains(const Sequence &values, const typename Sequence::value_type &wanted) { return Int(std::any_of(values.begin(), values.end(), [&](const auto &value) { return static_cast(value == wanted); })); } template Int lower_bound_index(const Sequence &values, const typename Sequence::value_type &wanted) { return Int(std::lower_bound(values.begin(), values.end(), wanted, ordered_less) - values.begin()); } template Int upper_bound_index(const Sequence &values, const typename Sequence::value_type &wanted) { return Int(std::upper_bound(values.begin(), values.end(), wanted, ordered_less) - values.begin()); } template SequenceIterator lower_bound(const Sequence &values, const typename Sequence::value_type &wanted) { return fken::begin(values) + lower_bound_index(values, wanted); } template SequenceIterator upper_bound(const Sequence &values, const typename Sequence::value_type &wanted) { return fken::begin(values) + upper_bound_index(values, wanted); } template bool binary_search(const Sequence &values, const typename Sequence::value_type &wanted) { return std::binary_search(values.begin(), values.end(), wanted, ordered_less); } template void append(std::vector &destination, const std::vector &suffix) { destination.insert(destination.end(), suffix.begin(), suffix.end()); } template std::vector concat(std::vector prefix, const std::vector &suffix) { append(prefix, suffix); return prefix; } inline Int at_least(const Array &values, const Int &x) { return Int(std::lower_bound(values.begin(), values.end(), x, integer_less) - values.begin()); } inline Int more_than(const Array &values, const Int &x) { return Int(std::upper_bound(values.begin(), values.end(), x, integer_less) - values.begin()); } inline Int at_most(const Array &values, const Int &x) { return more_than(values, x) - Int(1); } inline Int less_than(const Array &values, const Int &x) { return at_least(values, x) - Int(1); } template Int binary_search(Int ng, Int ok, const Check &check) { if (!ng.is_finite() || !ok.is_finite() || ng == ok) throw std::domain_error("binary search requires distinct finite endpoints"); for (;;) { const Int distance = ok - ng; if (distance >= Int(-1) && distance <= Int(1)) return ok; Int middle = ng + distance / Int(2); if (check(middle)) ok = std::move(middle); else ng = std::move(middle); } } template Int at_least(Int ng, Int ok, const Function &f, const Key &key) { return binary_search(std::move(ng), std::move(ok), [&](const Int &x) { return f(x) >= key; }); } template Int more_than(Int ng, Int ok, const Function &f, const Key &key) { return binary_search(std::move(ng), std::move(ok), [&](const Int &x) { return f(x) > key; }); } template Int at_most(Int ng, Int ok, const Function &f, const Key &key) { return binary_search(std::move(ng), std::move(ok), [&](const Int &x) { return f(x) <= key; }); } template Int less_than(Int ng, Int ok, const Function &f, const Key &key) { return binary_search(std::move(ng), std::move(ok), [&](const Int &x) { return f(x) < key; }); } inline double real_midpoint(double a, double b) { constexpr double half_max = std::numeric_limits::max() / 2; constexpr double twice_min = std::numeric_limits::min() * 2; if (std::abs(a) <= half_max && std::abs(b) <= half_max) return (a + b) / 2; if (std::abs(a) < twice_min) return a + b / 2; if (std::abs(b) < twice_min) return a / 2 + b; return a / 2 + b / 2; } template double binary_search(double ng, double ok, const Check &check, Int iterations = Int(100)) { if (!std::isfinite(ng) || !std::isfinite(ok) || ng == ok) throw std::domain_error("binary search requires distinct finite endpoints"); if (!iterations.is_finite() || iterations < Int(0)) throw std::domain_error("binary search requires a finite nonnegative iteration limit"); for (; iterations; iterations -= Int(1)) { const double middle = real_midpoint(ng, ok); if (middle == ng || middle == ok) break; if (check(middle)) ok = middle; else ng = middle; } return ok; } template double at_least(double ng, double ok, const Function &f, const Key &key, const Int &iterations = Int(100)) { return binary_search(ng, ok, [&](double x) { return f(x) >= key; }, iterations); } template double more_than(double ng, double ok, const Function &f, const Key &key, const Int &iterations = Int(100)) { return binary_search(ng, ok, [&](double x) { return f(x) > key; }, iterations); } template double at_most(double ng, double ok, const Function &f, const Key &key, const Int &iterations = Int(100)) { return binary_search(ng, ok, [&](double x) { return f(x) <= key; }, iterations); } template double less_than(double ng, double ok, const Function &f, const Key &key, const Int &iterations = Int(100)) { return binary_search(ng, ok, [&](double x) { return f(x) < key; }, iterations); } inline std::vector run_length(const Array &values) { std::vector runs; for (const auto &value : values) { if (runs.empty() || runs.back().first != value) runs.emplace_back(value, Int(1)); else runs.back().second += Int(1); } return runs; } template Vec make_vec(const std::vector &shape, const Element &initial = Element{}, std::size_t dimension = 0) { if constexpr (Rank == 1 && std::is_same_v) { return std::string(shape[dimension], initial); } else if constexpr (Rank == 1) { return Vec(shape[dimension], initial); } else { Vec values(shape[dimension]); for (auto &child : values) child = make_vec(shape, initial, dimension + 1); return values; } } inline std::string read_string() { std::string value; if (!(std::cin >> value)) throw std::runtime_error("expected string input"); return value; } inline char read_char() { char value; if (!(std::cin >> value)) throw std::runtime_error("expected character input"); return value; } inline Int len(const std::string &value) { return Int(static_cast(value.size())); } inline Int size(const std::string &value) { return len(value); } inline void push_back(std::string &value, char c) { value.push_back(c); } inline void push(std::string &value, char c) { value.push_back(c); } inline void clear(std::string &value) { value.clear(); } inline void resize(std::string &value, const Int &n, char fill = '\0') { value.resize(n.to_size("string size"), fill); } inline char back(const std::string &value) { if (value.empty()) throw std::out_of_range("back of empty string"); return value.back(); } inline char pop(std::string &value) { char c = back(value); value.pop_back(); return c; } inline char &at(std::string &value, const Int &i) { return value.at(i.to_size("string index")); } inline const char &at(const std::string &value, const Int &i) { return value.at(i.to_size("string index")); } inline Int read_int() { std::string token; if (!(std::cin >> token)) throw std::runtime_error("expected integer input"); return Int::parse(token); } template void read_into(Int &value) { std::string token; if (!(std::cin >> token)) return; if constexpr (Boolean) { if (token == "true") value = Int(1); else if (token == "false") value = Int(0); else std::cin.setstate(std::ios::failbit); return; } try { Int input = Int::parse(token); if constexpr (Bits != 0) { if (!fits_width(input)) { std::cin.setstate(std::ios::failbit); return; } } value = std::move(input); } catch (const std::invalid_argument &) { std::cin.setstate(std::ios::failbit); } } inline void read_into(double &value) { std::string input; if (!(std::cin >> input)) return; char *end = nullptr; double candidate = std::strtod(input.c_str(), &end); if (end != input.c_str() + input.size() || !std::isfinite(candidate) || input.find_first_not_of("0123456789.eE+-") != std::string::npos) { std::cin.setstate(std::ios::failbit); return; } value = candidate; } inline void read_into(char &value) { char input; if (std::cin >> input) value = input; } inline void read_into(std::string &value) { std::string input; if (std::cin >> input) value = std::move(input); } template void read_into(Mint &value) { Int input; read_into(input); if (std::cin) { if (input.is_finite()) value = Mint(input); else std::cin.setstate(std::ios::failbit); } } inline void read_into(IntPair &value) { read_into(value.first); if (std::cin) read_into(value.second); } template requires requires(Sequence &values) { values.begin(); values.end(); } void read_into(Sequence &values) { for (auto &value : values) { if (!std::cin) break; if constexpr (Bits == 0 && !Boolean) read_into(value); else read_into(value); } } inline Array array(const Int &size, const Int &initial = Int(0)) { return Array(size.to_size("array size"), initial); } inline Array read_vec(const Int &size) { Array values = array(size); for (auto &value : values) value = read_int(); return values; } template Int len(const std::vector &values) { return Int(static_cast(values.size())); } template Int len(const FixedArray &values) { return Int(static_cast(values.size())); } template std::size_t checked_index(const Sequence &values, const Int &index) { auto position = index.to_size("array index"); if (position >= values.size()) throw std::out_of_range("array index is out of bounds"); return position; } template T &at(std::vector &values, const Int &index) { return values[checked_index(values, index)]; } template const T &at(const std::vector &values, const Int &index) { return values[checked_index(values, index)]; } template T &at(FixedArray &values, const Int &index) { return values.values[checked_index(values, index)]; } template const T &at(const FixedArray &values, const Int &index) { return values[checked_index(values, index)]; } struct Edge { Int to, cost, id; }; struct Diameter { Int dist, one, two; }; struct MstResult { Int cost; Array edge_ids; }; template class Graph; class ShortestPathResult { template friend class Graph; std::size_t source_ = 0; std::vector parent_; Array parent_edge_; ShortestPathResult(std::size_t source, std::size_t size) : source_(source), parent_(size, size), parent_edge_(size), dist(size, Int::infinity()) { dist[source] = Int(0); } Array restore(const Int &vertex, bool edges) const { auto v = checked_index(dist, vertex); if (!dist[v].is_finite()) throw std::domain_error("shortest path restoration requires a finite distance"); Array path; while (v != source_) { path.push_back(edges ? parent_edge_[v] : Int(static_cast(v))); v = parent_[v]; } if (!edges) path.emplace_back(static_cast(source_)); std::reverse(path.begin(), path.end()); return path; } public: Array dist; ShortestPathResult() = default; Int reachable(const Int &vertex) const { return at(dist, vertex) != Int::infinity(); } Array restore_vertices(const Int &vertex) const { return restore(vertex, false); } Array restore_edges(const Int &vertex) const { return restore(vertex, true); } }; class Tree { std::vector> up_; std::vector depths_; Array tour_, entry_, exit_; static Int number(std::size_t value) { return Int(static_cast(value)); } std::size_t lift(std::size_t vertex, std::size_t steps) const { for (std::size_t bit = 0; steps; ++bit, steps >>= 1) if (steps & 1) vertex = up_[bit][vertex]; return vertex; } std::size_t common_ancestor(std::size_t a, std::size_t b) const { if (depths_[a] < depths_[b]) std::swap(a, b); a = lift(a, depths_[a] - depths_[b]); if (a == b) return a; for (std::size_t bit = up_.size(); bit-- > 0;) { if (up_[bit][a] == up_[bit][b]) continue; a = up_[bit][a]; b = up_[bit][b]; } return up_[0][a]; } public: Tree() = default; Tree(const std::vector> &rows, const Int &root) { const auto n = rows.size(), start = checked_index(rows, root); up_.emplace_back(n, n); auto &parent = up_.front(); depths_.resize(n); entry_.resize(n); exit_.resize(n); std::vector> stack{{start, 0}}; parent[start] = start; tour_.push_back(number(start)); std::size_t visited = 1; while (!stack.empty()) { auto &[vertex, next] = stack.back(); if (next == rows[vertex].size()) { exit_[vertex] = number(visited); stack.pop_back(); if (!stack.empty()) tour_.push_back(number(stack.back().first)); continue; } auto child = rows[vertex][next++].to.to_size("vertex index"); if (parent[child] != n) continue; parent[child] = vertex; depths_[child] = depths_[vertex] + 1; entry_[child] = number(visited++); stack.emplace_back(child, 0); tour_.push_back(number(child)); } if (visited != n) throw std::invalid_argument("rooted tree requires a connected graph"); for (std::size_t remaining = n - 1; remaining > 1; remaining >>= 1) { const auto &previous = up_.back(); std::vector next(n); for (std::size_t v = 0; v < n; ++v) next[v] = previous[previous[v]]; up_.push_back(std::move(next)); } } Int size() const { return number(depths_.size()); } Int depth(const Int &v) const { return number(at(depths_, v)); } const Array &euler_tour() const { return tour_; } const Array &entry() const { return entry_; } const Array &exit() const { return exit_; } Int lca(const Int &a, const Int &b) const { return number(common_ancestor(checked_index(depths_, a), checked_index(depths_, b))); } Int jump(const Int &a, const Int &b, const Int &k) const { const auto u = checked_index(depths_, a), v = checked_index(depths_, b); const auto ancestor = common_ancestor(u, v); const auto first = depths_[u] - depths_[ancestor]; const auto distance = first + depths_[v] - depths_[ancestor]; if (k < Int(0) || k > number(distance)) return Int(-1); auto steps = k.to_size("step count"); return number(steps <= first ? lift(u, steps) : lift(v, distance - steps)); } }; template class Graph { std::vector> rows_; Int edge_count_; enum class PathMethod { automatic, unit, zero_one, dag, dijkstra, bellman_ford }; std::vector topological_order() const { const auto n = rows_.size(); std::vector indegree(n), order; for (const auto &row : rows_) for (const auto &edge : row) ++indegree[edge.to.to_size("vertex index")]; for (std::size_t v = 0; v < n; ++v) if (!indegree[v]) order.push_back(v); for (std::size_t i = 0; i < order.size(); ++i) for (const auto &edge : rows_[order[i]]) { auto v = edge.to.to_size("vertex index"); if (--indegree[v] == 0) order.push_back(v); } return order; } ShortestPathResult paths(const Int &source, PathMethod method) const { const auto n = rows_.size(), start = checked_index(rows_, source); bool unit = true, zero_one = true, nonnegative = true; std::vector sources; for (std::size_t u = 0; u < n; ++u) { if (rows_[u].empty()) continue; sources.push_back(u); for (const auto &edge : rows_[u]) { unit = unit && edge.cost == Int(1); zero_one = zero_one && (edge.cost == Int(0) || edge.cost == Int(1)); nonnegative = nonnegative && edge.cost >= Int(0); } } std::vector order; if (method == PathMethod::dag || (method == PathMethod::automatic && Directed && !zero_one)) order = topological_order(); if (method == PathMethod::automatic) { if (unit) method = PathMethod::unit; else if (zero_one) method = PathMethod::zero_one; else if (Directed && order.size() == n) method = PathMethod::dag; else if (nonnegative) method = PathMethod::dijkstra; else method = PathMethod::bellman_ford; } if (method == PathMethod::unit && !unit) throw std::domain_error("bfs requires edge weights of 1"); if (method == PathMethod::zero_one && !zero_one) throw std::domain_error("zero_one_bfs requires edge weights of 0 or 1"); if (method == PathMethod::dag && (!Directed || order.size() != n)) throw std::domain_error("dag_shortest_path requires a directed acyclic graph"); if (method == PathMethod::dijkstra && !nonnegative) throw std::domain_error("dijkstra requires nonnegative edge weights"); ShortestPathResult result(start, n); auto relax = [&](std::size_t u, std::size_t v, const Edge &edge) { Int candidate = result.dist[u] + edge.cost; if (candidate >= result.dist[v]) return false; result.dist[v] = std::move(candidate); result.parent_[v] = u; result.parent_edge_[v] = edge.id; return true; }; using Entry = std::pair; if (method == PathMethod::unit || method == PathMethod::zero_one) { std::deque queue{{Int(0), start}}; while (!queue.empty()) { auto [cost, u] = std::move(queue.front()); queue.pop_front(); if (cost != result.dist[u]) continue; for (const auto &edge : rows_[u]) { auto v = edge.to.to_size("vertex index"); if (!relax(u, v, edge)) continue; if (edge.cost == Int(0)) queue.emplace_front(result.dist[v], v); else queue.emplace_back(result.dist[v], v); } } } else if (method == PathMethod::dag) { for (auto u : order) { if (!result.dist[u].is_finite()) continue; for (const auto &edge : rows_[u]) relax(u, edge.to.to_size("vertex index"), edge); } } else if (method == PathMethod::dijkstra) { auto greater = [](const Entry &a, const Entry &b) { return static_cast(a.first > b.first); }; std::priority_queue, decltype(greater)> queue(greater); queue.emplace(Int(0), start); while (!queue.empty()) { auto [cost, u] = queue.top(); queue.pop(); if (cost != result.dist[u]) continue; for (const auto &edge : rows_[u]) { auto v = edge.to.to_size("vertex index"); if (relax(u, v, edge)) queue.emplace(result.dist[v], v); } } } else { for (std::size_t round = 1; round < n; ++round) { bool changed = false; for (auto u : sources) { if (!result.dist[u].is_finite()) continue; for (const auto &edge : rows_[u]) if (relax(u, edge.to.to_size("vertex index"), edge)) changed = true; } if (!changed) return result; } // Seed every vertex that can still improve, then follow outgoing edges. std::vector unbounded(n, false); std::vector queue; auto mark = [&](std::size_t v) { if (!unbounded[v]) { unbounded[v] = true; queue.push_back(v); } }; for (auto u : sources) { if (!result.dist[u].is_finite()) continue; for (const auto &edge : rows_[u]) { auto v = edge.to.to_size("vertex index"); if (result.dist[u] + edge.cost < result.dist[v]) mark(v); } } for (std::size_t i = 0; i < queue.size(); ++i) for (const auto &edge : rows_[queue[i]]) mark(edge.to.to_size("vertex index")); for (auto v : queue) result.dist[v] = -Int::infinity(); } return result; } public: explicit Graph(const Int &n = Int(0)) : rows_(n.to_size("vertex count")) {} Int size() const { return len(rows_); } const Int &edge_count() const { return edge_count_; } const std::vector &neighbors(const Int &u) const { return at(rows_, u); } ShortestPathResult shortest_path(const Int &source) const { return paths(source, PathMethod::automatic); } ShortestPathResult bfs_shortest_path(const Int &source) const { return paths(source, PathMethod::unit); } ShortestPathResult zero_one_bfs(const Int &source) const { return paths(source, PathMethod::zero_one); } ShortestPathResult dag_shortest_path(const Int &source) const { return paths(source, PathMethod::dag); } ShortestPathResult dijkstra_shortest_path(const Int &source) const { return paths(source, PathMethod::dijkstra); } ShortestPathResult bellman_ford(const Int &source) const { return paths(source, PathMethod::bellman_ford); } Array bfs(const Int &source) const { const auto start = checked_index(rows_, source); Array distance(rows_.size(), Int(-1)); std::vector queue{start}; distance[start] = Int(0); for (std::size_t i = 0; i < queue.size(); ++i) { const auto u = queue[i]; for (const auto &edge : rows_[u]) { auto v = edge.to.to_size("vertex index"); if (distance[v] != Int(-1)) continue; distance[v] = distance[u] + Int(1); queue.push_back(v); } } return distance; } Array dijkstra(const Int &source) const { const auto start = checked_index(rows_, source); using Entry = std::pair; auto greater = [](const Entry &a, const Entry &b) { return static_cast(a.first > b.first); }; std::priority_queue, decltype(greater)> queue(greater); Array distance(rows_.size(), Int(-1)); distance[start] = Int(0); queue.emplace(Int(0), start); while (!queue.empty()) { auto [cost, u] = queue.top(); queue.pop(); if (cost != distance[u]) continue; for (const auto &edge : rows_[u]) { if (edge.cost < Int(0)) throw std::domain_error("dijkstra requires nonnegative edge weights"); auto v = edge.to.to_size("vertex index"); Int candidate = cost + edge.cost; if (distance[v] != Int(-1) && candidate >= distance[v]) continue; distance[v] = candidate; queue.emplace(std::move(candidate), v); } } return distance; } Array components() const { Array component(rows_.size(), Int(-1)); Int next(0); std::vector queue; for (std::size_t start = 0; start < rows_.size(); ++start) { if (component[start] != Int(-1)) continue; component[start] = next; queue.assign(1, start); for (std::size_t i = 0; i < queue.size(); ++i) { for (const auto &edge : rows_[queue[i]]) { auto v = edge.to.to_size("vertex index"); if (component[v] != Int(-1)) continue; component[v] = next; queue.push_back(v); } } next += Int(1); } return component; } Tree tree(const Int &root = Int(0)) const { if (rows_.empty() || edge_count_ != Int(static_cast(rows_.size() - 1))) throw std::invalid_argument("rooted tree requires a nonempty tree"); return Tree(rows_, root); } MstResult mst() const { const std::size_t n = rows_.size(); if (n == 0) throw std::invalid_argument("mst requires a nonempty connected graph"); struct Candidate { std::size_t from, to; const Edge *edge; }; std::vector edges; for (std::size_t u = 0; u < n; ++u) { for (const auto &edge : rows_[u]) { auto v = edge.to.to_size("vertex index"); if (u < v) edges.push_back({u, v, &edge}); } } std::sort(edges.begin(), edges.end(), [](const Candidate &a, const Candidate &b) { if (a.edge->cost == b.edge->cost) return static_cast(a.edge->id < b.edge->id); return static_cast(a.edge->cost < b.edge->cost); }); std::vector parent(n), sizes(n, 1); for (std::size_t v = 0; v < n; ++v) parent[v] = v; auto root = [&](std::size_t v) { while (parent[v] != v) { parent[v] = parent[parent[v]]; v = parent[v]; } return v; }; MstResult result{}; for (const auto &[from, to, edge] : edges) { auto a = root(from), b = root(to); if (a == b) continue; if (sizes[a] < sizes[b]) std::swap(a, b); parent[b] = a; sizes[a] += sizes[b]; result.cost += edge->cost; result.edge_ids.push_back(edge->id); if (result.edge_ids.size() == n - 1) break; } if (result.edge_ids.size() != n - 1) throw std::invalid_argument("mst requires a connected graph"); return result; } Diameter diameter() const { const auto n = rows_.size(); if (n == 0 || edge_count_ != Int(static_cast(n - 1))) throw std::invalid_argument("diameter requires a nonempty undirected tree"); auto farthest = [&](std::size_t start) { std::vector dist(n, Int(-1)); std::vector order{start}; dist[start] = Int(0); auto best = start; for (std::size_t i = 0; i < order.size(); ++i) { auto u = order[i]; for (const auto &edge : rows_[u]) { if (edge.cost < Int(0)) throw std::invalid_argument("diameter requires nonnegative edge weights"); auto v = edge.to.to_size("vertex index"); if (dist[v] >= Int(0)) continue; dist[v] = dist[u] + edge.cost; order.push_back(v); if (best == start || dist[v] > dist[best]) best = v; } } if (order.size() != n) throw std::invalid_argument("diameter requires a connected tree"); return std::pair(best, std::move(dist[best])); }; auto [one, ignored] = farthest(0); auto [two, dist] = farthest(one); return {std::move(dist), Int(static_cast(one)), Int(static_cast(two))}; } Int add(const Int &u, const Int &v, const Int &cost = Int(1)) { if (!cost.is_finite()) throw std::domain_error("edge weight must be finite"); auto &from = at(rows_, u); auto &to = at(rows_, v); const Int id = edge_count_; Int next = id + Int(1); from.push_back({v, cost, id}); if constexpr (!Directed) { try { to.push_back({u, cost, id}); } catch (...) { from.pop_back(); throw; } } edge_count_ = std::move(next); return id; } }; template const std::vector &at(const Graph &graph, const Int &u) { return graph.neighbors(u); } template struct KeyLess { bool operator()(const Key &a, const Key &b) const { if constexpr (std::is_same_v) return static_cast(a) < static_cast(b); return static_cast(a < b); } }; template struct KeyEqual { bool operator()(const Key &a, const Key &b) const { return static_cast(a == b); } }; template struct KeyHash { std::size_t operator()(const Key &key) const { if constexpr (std::is_same_v) return key.hash(); else return std::hash{}(key); } }; template class Associative { static constexpr bool is_map = Kind < 4; static constexpr bool multi = (Kind & 2) != 0; struct SetGroup { std::size_t count = 0, order = 0; }; using Group = std::conditional_t, Value>, SetGroup>; using Ordered = std::map>; using Unordered = std::unordered_map, KeyEqual>; std::conditional_t<(Kind & 1) != 0, Unordered, Ordered> groups_; std::size_t total_ = 0; std::size_t next_order_ = 0; mutable std::vector> ranked_; void rank_keys() const requires (!is_map) { if (ranked_.size() == groups_.size()) return; using Entry = typename decltype(groups_)::value_type; std::vector entries; entries.reserve(groups_.size()); for (const auto &entry : groups_) entries.push_back(&entry); if constexpr ((Kind & 1) != 0) { std::sort(entries.begin(), entries.end(), [](const Entry *a, const Entry *b) { return a->second.order < b->second.order; }); } // Publish the new cache only after all key copies succeeded. std::vector> ranked; ranked.reserve(entries.size()); std::size_t end = 0; for (const auto *entry : entries) { end += entry->second.count; ranked.emplace_back(entry->first, end); } ranked_ = std::move(ranked); } static std::size_t occurrences(const Group &group) { if constexpr (!is_map) return group.count; else if constexpr (multi) return group.size(); else return 1; } static Associative combine(const Associative &left, const Associative &right, char op) requires (Kind == 4) { Associative result; auto from_left = left.groups_.begin(), end_left = left.groups_.end(); auto from_right = right.groups_.begin(), end_right = right.groups_.end(); auto output = std::inserter(result.groups_, result.groups_.end()); auto less = [](const auto &a, const auto &b) { return KeyLess{}(a.first, b.first); }; switch (op) { case '|': std::set_union(from_left, end_left, from_right, end_right, output, less); break; case '&': std::set_intersection(from_left, end_left, from_right, end_right, output, less); break; case '-': std::set_difference(from_left, end_left, from_right, end_right, output, less); break; case '^': std::set_symmetric_difference(from_left, end_left, from_right, end_right, output, less); break; } result.next_order_ = result.groups_.size(); return result; } public: friend Associative operator|(const Associative &left, const Associative &right) requires (Kind == 4) { return combine(left, right, '|'); } friend Associative operator&(const Associative &left, const Associative &right) requires (Kind == 4) { return combine(left, right, '&'); } friend Associative operator-(const Associative &left, const Associative &right) requires (Kind == 4) { return combine(left, right, '-'); } friend Associative operator^(const Associative &left, const Associative &right) requires (Kind == 4) { return combine(left, right, '^'); } Int size() const { return Int(static_cast(multi ? total_ : groups_.size())); } Int count(const Key &key) const { const auto found = groups_.find(key); return Int(found == groups_.end() ? 0 : static_cast(occurrences(found->second))); } Int contains(const Key &key) const { return Int(groups_.find(key) != groups_.end()); } Int erase(const Key &key) { const auto found = groups_.find(key); if (found == groups_.end()) return Int(0); auto removed = occurrences(found->second); groups_.erase(found); if constexpr (!is_map) ranked_.clear(); if constexpr (multi) total_ -= removed; return Int(static_cast(removed)); } Vec<1, Key> keys() const { Vec<1, Key> keys; keys.reserve(groups_.size()); if constexpr (is_map) { for (const auto &[key, group] : groups_) keys.push_back(key); } else { rank_keys(); for (const auto &[key, end] : ranked_) keys.push_back(key); } return keys; } void insert(Key key, Value value) requires is_map { if constexpr (multi) { auto [position, created] = groups_.try_emplace(std::move(key)); try { position->second.push_back(std::move(value)); } catch (...) { if (created) groups_.erase(position); throw; } ++total_; } else { groups_.insert_or_assign(std::move(key), std::move(value)); } } void insert(Key key) requires (!is_map) { auto [it, created] = groups_.try_emplace(std::move(key)); if (created) it->second.order = next_order_++; if constexpr (multi) { ++it->second.count; ++total_; } else it->second.count = 1; if (created || multi) ranked_.clear(); } Value &index(const Key &key) requires (is_map && !multi) { return groups_[key]; } auto index(const Key &key) const requires is_map { const auto found = groups_.find(key); return found == groups_.end() ? Group{} : found->second; } Key at_rank(const Int &index) const requires (!is_map) { auto i = index.to_size("set index"); rank_keys(); if constexpr (!multi) return ranked_.at(i).first; const auto found = std::upper_bound(ranked_.begin(), ranked_.end(), i, [](auto position, const auto &entry) { return position < entry.second; }); if (found == ranked_.end()) throw std::out_of_range("set index is out of bounds"); return found->first; } }; template decltype(auto) at(Associative &values, const std::conditional_t<(Kind < 4), Key, Int> &key) { if constexpr (Kind < 4) return values.index(key); else return values.at_rank(key); } template auto at(const Associative &values, const std::conditional_t<(Kind < 4), Key, Int> &key) { if constexpr (Kind < 4) return values.index(key); else return values.at_rank(key); } template class Deque { std::deque values_; public: Int size() const { return Int(static_cast(values_.size())); } Int empty() const { return Int(values_.empty()); } void clear() { values_.clear(); } void push_front(T value) { values_.push_front(std::move(value)); } void push_back(T value) { values_.push_back(std::move(value)); } const T &front() const { return values_.at(0); } const T &back() const { if (values_.empty()) throw std::out_of_range("deque is empty"); return values_.back(); } T pop_front() { if (values_.empty()) throw std::out_of_range("deque is empty"); T value = std::move(values_.front()); values_.pop_front(); return value; } T pop_back() { if (values_.empty()) throw std::out_of_range("deque is empty"); T value = std::move(values_.back()); values_.pop_back(); return value; } T &index(const Int &i) { return values_.at(i.to_size("deque index")); } const T &index(const Int &i) const { return values_.at(i.to_size("deque index")); } }; template T &at(Deque &values, const Int &i) { return values.index(i); } template const T &at(const Deque &values, const Int &i) { return values.index(i); } template class Adapter { Storage values_; using T = typename Storage::value_type; void require_value() const { if (values_.empty()) throw std::out_of_range("container adapter is empty"); } public: Int size() const { return Int(values_.size()); } bool empty() const { return values_.empty(); } void clear() { values_ = Storage{}; } void push(T value) { values_.push(std::move(value)); } T front() const { require_value(); return values_.front(); } T back() const { require_value(); return values_.back(); } T top() const { require_value(); return values_.top(); } T pop() { require_value(); T value = [&]() -> T { if constexpr (requires { values_.front(); }) return std::move(values_.front()); else return std::move(values_.top()); }(); values_.pop(); return value; } }; template using Queue = Adapter>; template using Stack = Adapter>; template using PriorityQueue = Adapter, std::decay_t>>; template Values &at_path(Values &values) { return values; } template decltype(auto) at_path(Values &values, const Int &index, const Rest &...rest) { return at_path(at(values, index), rest...); } template void push(std::vector &values, T value) { values.push_back(std::move(value)); } template T pop(std::vector &values) { if (values.empty()) throw std::out_of_range("pop from empty vector"); T result = std::move(values.back()); values.pop_back(); return result; } template T back(const std::vector &values) { if (values.empty()) throw std::out_of_range("back of empty vector"); return values.back(); } template Int size(const std::vector &values) { return len(values); } template void resize(std::vector &values, const Int &count, T initial = T{}) { values.resize(count.to_size("vector size"), initial); } template void clear(std::vector &values) { values.clear(); } inline void write_boolean(std::ostream &out, bool value) { out << (value ? "true" : "false"); } inline void write_boolean(std::ostream &out, const Int &value) { write_boolean(out, static_cast(value)); } template void write_boolean(std::ostream &out, const Sequence &values) { constexpr bool nested = !std::is_same_v; for (std::size_t i = 0; i < values.size(); ++i) { if (i) out << ' '; if constexpr (nested) out << '['; write_boolean(out, values[i]); if constexpr (nested) out << ']'; } } inline std::ostream &operator<<(std::ostream &out, const IntPair &value) { return out << value.first << ' ' << value.second; } template std::ostream &write_sequence(std::ostream &out, const Sequence &values); template void write_component(std::ostream &out, const T &value) { constexpr bool sequence = requires { value.begin(); value.end(); } && !std::is_same_v; constexpr bool compound = sequence || std::is_same_v || requires { typename T::fken_product; }; if constexpr (compound) out << '['; if constexpr (Boolean) write_boolean(out, value); else if constexpr (sequence) write_sequence(out, value); else out << value; if constexpr (compound) out << ']'; } template std::ostream &write_sequence(std::ostream &out, const Sequence &values) { for (std::size_t i = 0; i < values.size(); i++) { if (i) out << ' '; write_component(out, values[i]); } return out; } template std::ostream &operator<<(std::ostream &out, const std::vector &values) { return write_sequence(out, values); } template std::ostream &operator<<(std::ostream &out, const FixedArray &values) { return write_sequence(out, values); } template void write_matrix(std::ostream &out, const Sequence &rows) { for (std::size_t i = 0; i < rows.size(); ++i) { if (i) out << '\n'; if constexpr (Boolean) write_boolean(out, rows[i]); else out << rows[i]; } } } // namespace fken #endif using FkenAssoc0 = fken::Deque; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.precision(20); std::cerr.precision(20); try { FkenAssoc0 fken_v8 = FkenAssoc0{}; fken::Int fken_v16 = fken::Int{}; { ([&]() { using fken::read_into; read_into(fken_v16); }()); } fken::Array fken_v24 = ([&]() { std::size_t fken_size0 = (fken_v16).to_size("array size"); return fken::make_vec<1,fken::Int>({fken_size0}); }()); { ([&]() { using fken::read_into; read_into(fken_v24); }()); } ([&]() -> void { fken::Int fken_arg0 = (-fken::Int(INT64_C(1))); return fken_v8.push_back(std::move(fken_arg0)); }()); ([&]() -> void { fken::Int fken_arg0 = (-fken::Int(INT64_C(2))); return fken_v8.push_back(std::move(fken_arg0)); }()); ([&]() -> void { fken::Int fken_arg0 = (-fken::Int(INT64_C(3))); return fken_v8.push_back(std::move(fken_arg0)); }()); fken::Int fken_v32 = fken::Int(INT64_C(0)); { fken::Int fken_start = fken::Int(INT64_C(0)); fken::Int fken_end = fken_v16; for (fken::Int fken_v40 = fken::rep_boundary(std::move(fken_start)), fken_bound = fken::rep_boundary(std::move(fken_end)); fken_v40 < fken_bound; fken_v40 += fken::Int(1)) { { { ([&]() -> void { fken::Int fken_arg0 = ([&]() -> fken::Int { fken::Int fken_index0 = fken_v40; fken::at(fken_v24, fken_index0); return fken::at(fken_v24, fken_index0); }()); return fken_v8.push_back(std::move(fken_arg0)); }()); fken::Int fken_v48 = ([&]() -> fken::Int { return fken_v8.size(); }()); if (fken::Int((([&]() { fken::Int fken_left = ([&]() -> fken::Int { fken::Int fken_index0 = ([&]() { fken::Int fken_left = fken_v48; fken::Int fken_right = fken::Int(INT64_C(1)); return fken_left - fken_right; }()); fken::at(fken_v8, fken_index0); return fken::at(fken_v8, fken_index0); }()); fken::Int fken_right = ([&]() -> fken::Int { fken::Int fken_index0 = ([&]() { fken::Int fken_left = fken_v48; fken::Int fken_right = fken::Int(INT64_C(2)); return fken_left - fken_right; }()); fken::at(fken_v8, fken_index0); return fken::at(fken_v8, fken_index0); }()); return fken_left == fken_right; }())) && (([&]() { fken::Int fken_left = ([&]() -> fken::Int { fken::Int fken_index0 = ([&]() { fken::Int fken_left = fken_v48; fken::Int fken_right = fken::Int(INT64_C(2)); return fken_left - fken_right; }()); fken::at(fken_v8, fken_index0); return fken::at(fken_v8, fken_index0); }()); fken::Int fken_right = ([&]() -> fken::Int { fken::Int fken_index0 = ([&]() { fken::Int fken_left = fken_v48; fken::Int fken_right = fken::Int(INT64_C(3)); return fken_left - fken_right; }()); fken::at(fken_v8, fken_index0); return fken::at(fken_v8, fken_index0); }()); return fken_left == fken_right; }())))) { ([&]() -> decltype(auto) { fken::Int fken_value = fken::Int(INT64_C(3)); auto &fken_target = fken_v32; fken_target += std::move(fken_value); return (fken_target); }()); { fken::Int fken_start = fken::Int(INT64_C(0)); fken::Int fken_end = fken::Int(INT64_C(3)); for (fken::Int fken_v56 = fken::rep_boundary(std::move(fken_start)), fken_bound = fken::rep_boundary(std::move(fken_end)); fken_v56 < fken_bound; fken_v56 += fken::Int(1)) { { { ([&]() -> fken::Int { return fken_v8.pop_back(); }()); } } [[maybe_unused]] fken_continue_2: ; } [[maybe_unused]] fken_break_2: ; } } } } [[maybe_unused]] fken_continue_1: ; } [[maybe_unused]] fken_break_1: ; } { const auto &fken_arg0 = fken_v32; std::cout << fken_arg0; std::cout << '\n'; } return 0; } catch (const std::exception &error) { std::cerr << "runtime error: " << error.what() << '\n'; return 1; } }