結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー 37zigen
提出日時 2026-11-23 23:23:28
言語 C++23(gcc16)
(gcc 16.2.0 + boost 1.92.0 + ACL)
コンパイル:
g++-16 -O2 -fplugin=/usr/lib/yukicoder/noavx512-gcc16.so -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 1,865 ms / 2,000 ms
+ 214µs
コード長 126,906 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 5,748 ms
コンパイル使用メモリ 428,420 KB
実行使用メモリ 8,240 KB
スコア 1,457,625
最終ジャッジ日時 2026-11-23 23:25:15
合計ジャッジ時間 106,445 ms
ジャッジサーバーID
(参考情報)
judge4_0 / judge1_0
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;

template<class T, class = void> struct jhas_key : false_type {};
template<class T> struct jhas_key<T, void_t<decltype(declval<T>()->key)>> : true_type {};
template<class T> struct jhas_key_obj : false_type {};
template<class T> struct jhas_key<T, void_t<decltype(declval<T>().key)>> : true_type {};

using JString = std::string;
using JObject = std::any;

struct JClass {
    const std::type_info* info = &typeid(void);
    JClass() = default;
    JClass(const std::type_info& ti) : info(&ti) {}
    bool operator==(const JClass& o) const { return info && o.info && *info == *o.info; }
    bool operator!=(const JClass& o) const { return !(*this == o); }
};

struct JNumber {
    long long l_val = 0;
    double d_val = 0.0;
    bool is_fp = false;

    JNumber() = default;
    JNumber(long long v) : l_val(v), d_val(static_cast<double>(v)), is_fp(false) {}
    JNumber(int v) : l_val(v), d_val(v), is_fp(false) {}
    JNumber(double v) : l_val(static_cast<long long>(v)), d_val(v), is_fp(true) {}
    JNumber(float v) : l_val(static_cast<long long>(v)), d_val(v), is_fp(true) {}
    JNumber(int8_t v) : l_val(v), d_val(v), is_fp(false) {}
    JNumber(int16_t v) : l_val(v), d_val(v), is_fp(false) {}
    JNumber(const JObject& obj) {
        if (!obj.has_value()) { l_val = 0; d_val = 0; is_fp = false; }
        else if (auto p = std::any_cast<int>(&obj)) { l_val = *p; d_val = *p; is_fp = false; }
        else if (auto p = std::any_cast<long long>(&obj)) { l_val = *p; d_val = *p; is_fp = false; }
        else if (auto p = std::any_cast<double>(&obj)) { d_val = *p; l_val = static_cast<long long>(*p); is_fp = true; }
        else if (auto p = std::any_cast<float>(&obj)) { d_val = *p; l_val = static_cast<long long>(*p); is_fp = true; }
    }

    long long longValue() const { return is_fp ? static_cast<long long>(d_val) : l_val; }
    int intValue() const { return static_cast<int>(longValue()); }
    double doubleValue() const { return is_fp ? d_val : static_cast<double>(l_val); }
    float floatValue() const { return static_cast<float>(doubleValue()); }
    int8_t byteValue() const { return static_cast<int8_t>(longValue()); }
    int16_t shortValue() const { return static_cast<int16_t>(longValue()); }

    bool operator==(const JNumber& o) const {
        if (is_fp || o.is_fp) return doubleValue() == o.doubleValue();
        return longValue() == o.longValue();
    }
    bool operator!=(const JNumber& o) const { return !(*this == o); }
    bool operator<(const JNumber& o) const {
        if (is_fp || o.is_fp) return doubleValue() < o.doubleValue();
        return longValue() < o.longValue();
    }
    friend ostream& operator<<(ostream& os, const JNumber& n) {
        if (n.is_fp) os << n.d_val;
        else os << n.l_val;
        return os;
    }
};


namespace std {
    inline bool operator==(const any& a, const any& b) {
        if (!a.has_value() && !b.has_value()) return true;
        if (!a.has_value() || !b.has_value()) return false;
        return &a == &b;
    }
    inline bool operator!=(const any& a, const any& b) { return !(a == b); }
}

template<class T> bool jisInstance(const JObject& x) {
    return x.has_value() && (x.type() == typeid(T) || std::any_cast<T>(&x) != nullptr);
}
template<class T> bool jisInstance(const JObject& x, T& out) {
    if (x.has_value()) {
        if (auto p = std::any_cast<T>(&x)) { out = *p; return true; }
    }
    return false;
}
// 未テスト
// 計算量: O(1)
template<class T> struct jpointer_element { using type = T; };
template<class T> struct jpointer_element<std::shared_ptr<T>> { using type = T; };
template<class T> using jpointer_element_t = typename jpointer_element<T>::type;

template<class T, class U> bool jisInstance(const std::shared_ptr<U>& x) {
    using Target = jpointer_element_t<T>;
    if constexpr (std::is_base_of_v<Target, U>) {
        return x != nullptr;
    } else if constexpr (std::is_polymorphic_v<U> && (std::is_polymorphic_v<Target> || std::is_base_of_v<U, Target>)) {
        return std::dynamic_pointer_cast<Target>(x) != nullptr;
    } else {
        return false;
    }
}
// 未テスト
// 計算量: O(1)
template<class T, class U> bool jisInstance(const std::shared_ptr<U>&, T&) {
    return false;
}
// 未テスト
// 計算量: O(1)
template<class T, class U> bool jisInstance(const U& x) {
    if constexpr (std::is_same_v<T, U> || std::is_base_of_v<T, U>) return true;
    else return false;
}
// 未テスト
// 計算量: O(1)
template<class T, class U> bool jisInstance(const U& x, T& out) {
    if constexpr (std::is_same_v<T, U> || std::is_convertible_v<U, T>) {
        out = x;
        return true;
    } else {
        return false;
    }
}
// 未テスト
// 計算量: O(1)
template<class T, class U> bool jisInstance(const std::shared_ptr<U>& x, std::shared_ptr<T>& out) {
    if constexpr (std::is_base_of_v<T, U>) {
        if (x != nullptr) { out = std::static_pointer_cast<T>(x); return true; }
        return false;
    } else if constexpr (std::is_polymorphic_v<U> && (std::is_polymorphic_v<T> || std::is_base_of_v<U, T>)) {
        if (auto p = std::dynamic_pointer_cast<T>(x)) { out = p; return true; }
        return false;
    } else {
        return false;
    }
}

// 未テスト
// 計算量: O(1)
template<class Target, class Source>
Target jcast(Source&& src) {
    using CleanTarget = std::decay_t<Target>;
    using CleanSource = std::decay_t<Source>;
    if constexpr (std::is_convertible_v<Source, Target>) {
        return static_cast<Target>(std::forward<Source>(src));
    } else if constexpr (std::is_constructible_v<CleanTarget, Source>) {
        return CleanTarget(std::forward<Source>(src));
    } else {
        return CleanTarget{};
    }
}
inline std::vector<bool>::reference operator^=(std::vector<bool>::reference ref, bool val) { ref = ref ^ val; return ref; }
inline std::vector<bool>::reference operator&=(std::vector<bool>::reference ref, bool val) { ref = ref & val; return ref; }
inline std::vector<bool>::reference operator|=(std::vector<bool>::reference ref, bool val) { ref = ref | val; return ref; }

inline bool operator==(std::vector<bool>::reference a, std::vector<bool>::reference b) { return bool(a) == bool(b); }
inline bool operator!=(std::vector<bool>::reference a, std::vector<bool>::reference b) { return bool(a) != bool(b); }
inline bool operator==(std::vector<bool>::reference a, bool b) { return bool(a) == b; }
inline bool operator!=(std::vector<bool>::reference a, bool b) { return bool(a) != b; }
inline bool operator==(bool a, std::vector<bool>::reference b) { return a == bool(b); }
inline bool operator!=(bool a, std::vector<bool>::reference b) { return a != bool(b); }

template<class T> struct JOptionalVal;

template<class T>
struct NullableVal : public std::optional<T> {
    using std::optional<T>::optional;
    NullableVal() : std::optional<T>(std::nullopt) {}
    NullableVal(const std::optional<T>& o) : std::optional<T>(o) {}
    NullableVal(std::nullptr_t) : std::optional<T>(std::nullopt) {}
    NullableVal& operator=(std::nullptr_t) {
        this->reset();
        return *this;
    }
    operator T&() { return this->value(); }
    operator const T&() const { return this->value(); }
    bool operator==(std::nullptr_t) const { return !this->has_value(); }
    bool operator!=(std::nullptr_t) const { return this->has_value(); }
    bool operator==(const NullableVal<T>& o) const {
        return static_cast<const std::optional<T>&>(*this) == static_cast<const std::optional<T>&>(o);
    }
    bool operator!=(const NullableVal<T>& o) const {
        return !(*this == o);
    }
};

template<class T> struct jis_nullable_val : std::false_type {};
template<class T> struct jis_nullable_val<NullableVal<T>> : std::true_type {};

template<class T> struct jis_optional : std::false_type {};
template<class T> struct jis_optional<std::optional<T>> : std::true_type {};
template<class T> struct jis_optional<JOptionalVal<T>> : std::true_type {};

template<class T> struct jis_std_function : std::false_type {};
template<class R, class... Args> struct jis_std_function<std::function<R(Args...)>> : std::true_type {};

template<class T>
struct Nullable {
    using type = std::conditional_t<std::is_arithmetic_v<T>, NullableVal<T>, T>;
};

// 未テスト
// 計算量: O(1)
template<class T> bool jisNull(const T& x) {
    return false;
}
template<class T> bool jisNull(const NullableVal<T>& x) { return !x.has_value(); }
template<class T> bool jisNull(const std::optional<T>& x) { return !x.has_value(); }
template<class T> bool jisNull(const vector<T>& x) { return x.empty(); }
template<class T> bool jisNull(const shared_ptr<T>& x) { return !x; }
inline bool jisNull(const JObject& x) { return !x.has_value(); }
template<class R, class... Args>
inline bool jisNull(const std::function<R(Args...)>& f) { return !f; }

// 未テスト
// 計算量: O(1)
template<class T, class U, class = enable_if_t<(is_same_v<decay_t<T>, JObject> || is_same_v<decay_t<U>, JObject>) && !(is_same_v<decay_t<T>, JObject> && is_same_v<decay_t<U>, JObject>)>>
bool operator==(const T& a, const U& b) {
    if constexpr (is_same_v<decay_t<U>, JObject>) {
        if (!b.has_value()) return jisNull(a);
        return false;
    } else {
        return b == a;
    }
}
template<class T, class U, class = enable_if_t<(is_same_v<decay_t<T>, JObject> || is_same_v<decay_t<U>, JObject>) && !(is_same_v<decay_t<T>, JObject> && is_same_v<decay_t<U>, JObject>)>>
bool operator!=(const T& a, const U& b) {
    return !(a == b);
}

template<class K, class V>
struct JEntry {
    std::shared_ptr<std::pair<K, V>> ptr;
    JEntry() : ptr(nullptr) {}
    JEntry(std::nullptr_t) : ptr(nullptr) {}
    JEntry(const std::pair<K, V>& p) : ptr(std::make_shared<std::pair<K, V>>(p)) {}
    JEntry(std::pair<K, V>&& p) : ptr(std::make_shared<std::pair<K, V>>(std::move(p))) {}
    JEntry(const std::pair<const K, V>& p) : ptr(std::make_shared<std::pair<K, V>>(p.first, p.second)) {}
    JEntry(std::shared_ptr<std::pair<K, V>> p) : ptr(std::move(p)) {}

    std::pair<K, V>& operator*() { return *ptr; }
    const std::pair<K, V>& operator*() const { return *ptr; }
    std::pair<K, V>* operator->() { return ptr.get(); }
    const std::pair<K, V>* operator->() const { return ptr.get(); }

    bool operator==(std::nullptr_t) const { return ptr == nullptr; }
    bool operator!=(std::nullptr_t) const { return ptr != nullptr; }
    friend bool operator==(std::nullptr_t, const JEntry& e) { return e.ptr == nullptr; }
    friend bool operator!=(std::nullptr_t, const JEntry& e) { return e.ptr != nullptr; }
    bool operator<(const JEntry& o) const {
        if (!ptr) return (bool)o.ptr;
        if (!o.ptr) return false;
        return ptr->first < o.ptr->first;
    }

    operator bool() const { return ptr != nullptr; }
    operator std::pair<K, V>&() { return *ptr; }
    operator const std::pair<K, V>&() const { return *ptr; }

    const K& getKey() const { return ptr->first; }
    K& getKey() { return ptr->first; }
    const V& getValue() const { return ptr->second; }
    V& getValue() { return ptr->second; }
    void setValue(const V& v) { ptr->second = v; }
};

template<class K, class V> inline bool jisNull(const JEntry<K, V>& e) { return e.ptr == nullptr; }

template<class T, class = void> struct jis_pointer_like : std::false_type {};
template<class T> struct jis_pointer_like<T, std::void_t<decltype(std::declval<T>().operator->())>> : std::true_type {};

// 未テスト
// 計算量: O(1)
template<class T>
decltype(auto) jentryKey(T&& t) {
    if constexpr (jis_pointer_like<std::decay_t<T>>::value) {
        return (t->first);
    } else {
        return (t.first);
    }
}

// 未テスト
// 計算量: O(1)
template<class T>
decltype(auto) jentryValue(T&& t) {
    if constexpr (jis_pointer_like<std::decay_t<T>>::value) {
        return (t->second);
    } else {
        return (t.second);
    }
}

// 未テスト
// 計算量: O(1)
template<class T, class V>
decltype(auto) jentrySetValue(T&& t, V&& v) {
    if constexpr (jis_pointer_like<std::decay_t<T>>::value) {
        return (t->second = std::forward<V>(v));
    } else {
        return (t.second = std::forward<V>(v));
    }
}

// 未テスト
// 計算量: O(N)
template<class Dst, class Src>
void jassign(Dst& dst, Src&& src) {
    if constexpr (std::is_assignable_v<Dst&, Src>) {
        dst = std::forward<Src>(src);
    } else if constexpr (std::is_constructible_v<Dst, Src>) {
        dst = Dst(std::forward<Src>(src));
    } else {
        dst.clear();
        for (const auto& item : src) {
            typename Dst::value_type v;
            jassign(v, item);
            dst.push_back(v);
        }
    }
}

template<class T> struct JOptionalVal {
    std::optional<T> opt;
    JOptionalVal() : opt(std::nullopt) {}
    JOptionalVal(nullptr_t) : opt(std::nullopt) {}
    JOptionalVal(const T& val) : opt(val) {}
    JOptionalVal(const std::optional<T>& o) : opt(o) {}
    bool has_value() const { return opt.has_value(); }
    const T& value() const { return opt.value(); }
    const T& operator*() const { return opt.value(); }
    T& operator*() { return opt.value(); }
    template<class U = T, class = std::enable_if_t<!std::is_same_v<U, bool>>>
    operator U() const { return opt.value_or(U{}); }
    operator bool() const {
        if constexpr (std::is_same_v<T, bool>) {
            return opt.value_or(false);
        } else {
            return opt.has_value();
        }
    }
    friend bool operator==(const JOptionalVal& a, const JOptionalVal& b) { return a.opt == b.opt; }
    friend bool operator!=(const JOptionalVal& a, const JOptionalVal& b) { return a.opt != b.opt; }
    friend bool operator==(const JOptionalVal& a, nullptr_t) { return !a.opt.has_value(); }
    friend bool operator!=(const JOptionalVal& a, nullptr_t) { return a.opt.has_value(); }
    friend bool operator==(nullptr_t, const JOptionalVal& a) { return !a.opt.has_value(); }
    friend bool operator!=(nullptr_t, const JOptionalVal& a) { return a.opt.has_value(); }
    friend ostream& operator<<(ostream& os, const JOptionalVal& a) {
        if (a.opt.has_value()) return os << a.opt.value();
        return os << "null";
    }
};
template<class T> inline bool jisNull(const JOptionalVal<T>& x) { return !x.has_value(); }
struct JStringTokenizer;
inline bool jisNull(const JStringTokenizer& x);

template<class T, class = void> struct jhas_ostream : false_type {};
template<class T> struct jhas_ostream<T, void_t<decltype(declval<ostream&>() << declval<const T&>())>> : true_type {};

template<class T, class = void> struct jhas_toString : false_type {};
template<class T> struct jhas_toString<T, void_t<decltype(declval<const T&>().toString())>> : true_type {};

template<class T, class = void> struct jhas_ptr_toString : false_type {};
template<class T> struct jhas_ptr_toString<T, void_t<decltype(declval<const T&>()->toString())>> : true_type {};

template<class T> string jstr(const T& x);

// 未テスト
// 計算量: O(|a|)
inline string jstr(const vector<char>& a) {
    return string(a.begin(), a.end());
}

// 未テスト
// 計算量: O(|a| * len(jstr(elem)))
template<class T> string jstr(const vector<T>& a) {
    string s = "[";
    for (size_t i = 0; i < a.size(); ++i) s += (i ? ", " : "") + jstr(a[i]);
    return s + "]";
}

// Java の Double.toString() と同一の変換規則:
//   |x| < 1e-3 または |x| >= 1e7 なら指数表記 (大文字 E, 指数に + なし)、それ以外は小数表記。
//   shortest round-trip 表現 (C++17 std::to_chars の default モード)。
//   整数値の double は ".0" を末尾に付加。
// 計算量: O(1)
inline string jdouble_to_string(double x) {
    if (isnan(x)) return "NaN";
    if (x == numeric_limits<double>::infinity()) return "Infinity";
    if (x == -numeric_limits<double>::infinity()) return "-Infinity";

    double ax = abs(x);
    bool useScientific = (x != 0.0) && (ax >= 1e7 || ax < 1e-3);

    string result;
    char buf[64];

    if (!useScientific) {
        // C++ shortest round-trip via to_chars default (chooses shorter of decimal/scientific)
        auto [ptr, ec] = to_chars(buf, buf + sizeof(buf), x);
        *ptr = '\0';
        string s(buf);
        if (s.find('e') == string::npos) {
            result = s;
        } else {
            // C++ chose scientific but Java wants decimal — find shortest decimal that round-trips
            result.clear();
            for (int p = 1; p <= 17; ++p) {
                ostringstream oss;
                oss << setprecision(p) << x;
                string t = oss.str();
                if (t.find('e') == string::npos && stod(t) == x) {
                    result = t;
                    break;
                }
            }
            if (result.empty()) {
                ostringstream oss;
                oss << setprecision(17) << x;
                result = oss.str();
            }
        }
    } else {
        // Find shortest scientific representation that round-trips
        for (int p = 1; p <= 17; ++p) {
            auto [ptr, ec] = to_chars(buf, buf + sizeof(buf), x, chars_format::scientific, p);
            *ptr = '\0';
            if (stod(buf) == x) {
                result = string(buf);
                break;
            }
        }
        if (result.empty()) {
            auto [ptr, ec] = to_chars(buf, buf + sizeof(buf), x, chars_format::scientific, 17);
            *ptr = '\0';
            result = string(buf);
        }
        // Convert C++ exponent to Java format: e+01 -> E1, e-01 -> E-1
        auto ep = result.find('e');
        if (ep != string::npos) {
            result[ep] = 'E';
            size_t after_e = ep + 1;
            bool neg_exp = (result[after_e] == '-');
            if (result[after_e] == '+' || result[after_e] == '-') after_e++;
            // Remove leading zeros in exponent magnitude
            size_t first_nz = result.find_first_not_of('0', after_e);
            if (first_nz == string::npos) first_nz = result.size() - 1;
            if (first_nz > after_e) result.erase(after_e, first_nz - after_e);
            // Remove '+' sign (keep '-')
            if (!neg_exp && result[ep + 1] == '+') result.erase(ep + 1, 1);
        }
        // Ensure "X.0ENN" form when no decimal point before exponent
        auto ep2 = result.find('E');
        if (ep2 != string::npos && result.find('.') == string::npos) {
            result.insert(ep2, ".0");
        }
    }

    // Append ".0" for integer-valued finite doubles with no decimal point and no exponent
    if (isfinite(x) && result.find('.') == string::npos && result.find('E') == string::npos) {
        result += ".0";
    }
    return result;
}

// 未テスト
// 計算量: O(len(jstr(x)))
template<class T> string jstr(const T& x) {
    if constexpr (is_same_v<decay_t<T>, JObject>) {
        if (!x.has_value()) return "null";
        if (auto p = std::any_cast<int>(&x)) return std::to_string(*p);
        if (auto p = std::any_cast<long long>(&x)) return std::to_string(*p);
        if (auto p = std::any_cast<double>(&x)) return jdouble_to_string(*p);
        if (auto p = std::any_cast<JString>(&x)) return *p;
        return "<object>";
    } else if constexpr (jhas_toString<T>::value) {
        return x.toString();
    } else if constexpr (jhas_ptr_toString<T>::value) {
        return x ? x->toString() : "null";
    } else if constexpr (jhas_ostream<T>::value) {
        if constexpr (is_floating_point_v<decay_t<T>>) {
            return jdouble_to_string(static_cast<double>(x));
        } else {
            ostringstream o;
            o << x;
            return o.str();
        }
    } else {
        return "<object>";
    }
}

template<class A, class B> JString jconcat(const A& a, const B& b) { return jstr(a) + jstr(b); }
inline JString jrepeat(const JString& s, int n) { JString r; while (n-- > 0) r += s; return r; }
inline bool jstartsWith(const JString& s, const JString& prefix) {
    return s.rfind(prefix, 0) == 0;
}
inline bool jendsWith(const JString& s, const JString& suffix) {
    if (suffix.size() > s.size()) return false;
    return s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
}
// 未テスト
// 計算量: O(|s| * |target|)
inline bool jcontains(const JString& s, const JString& target) {
    return s.find(target) != JString::npos;
}
// 未テスト
// 計算量: O(|s|)
inline bool jmatches(const JString& s, const JString& regex) {
    try {
        return regex_match(s, std::regex(regex));
    } catch (...) {
        return false;
    }
}
inline JString jreplace(JString s, const JString& target, const JString& replacement) {
    if (target.empty()) return s;
    size_t pos = 0;
    while ((pos = s.find(target, pos)) != JString::npos) {
        s.replace(pos, target.length(), replacement);
        pos += replacement.length();
    }
    return s;
}
inline JString jreplace(JString s, char target, char replacement) {
    for (char& c : s) {
        if (c == target) c = replacement;
    }
    return s;
}
inline JString jreplaceAll(JString s, const JString& regex, const JString& replacement) {
    try {
        return regex_replace(s, std::regex(regex), replacement);
    } catch (...) {
        return jreplace(s, regex, replacement);
    }
}
// 未テスト
// 計算量: O(|s|)
inline JString jreplaceFirst(JString s, const JString& regex, const JString& replacement) {
    try {
        return regex_replace(s, std::regex(regex), replacement, std::regex_constants::format_first_only);
    } catch (...) {
        return jreplace(s, regex, replacement);
    }
}
// 未テスト
// 計算量: O(|s|)
inline JString jtrim(const JString& s) {
    size_t start = 0;
    while (start < s.size() && ::isspace(static_cast<unsigned char>(s[start]))) ++start;
    size_t end = s.size();
    while (end > start && ::isspace(static_cast<unsigned char>(s[end - 1]))) --end;
    return s.substr(start, end - start);
}
// 未テスト
// 計算量: O(|s|)
inline JString jstrip(const JString& s) { return jtrim(s); }
// 未テスト
// 計算量: O(|s|)
inline JString jstripLeading(const JString& s) {
    size_t start = 0;
    while (start < s.size() && ::isspace(static_cast<unsigned char>(s[start]))) ++start;
    return s.substr(start);
}
// 未テスト
// 計算量: O(|s|)
inline JString jstripTrailing(const JString& s) {
    size_t end = s.size();
    while (end > 0 && ::isspace(static_cast<unsigned char>(s[end - 1]))) --end;
    return s.substr(0, end);
}
// 未テスト
// 計算量: O(|s|)
inline bool jisBlank(const JString& s) {
    for (char c : s) {
        if (!::isspace(static_cast<unsigned char>(c))) return false;
    }
    return true;
}
// 未テスト
// 計算量: O(sum |elements|)
inline JString jjoin(const JString& delimiter, const vector<JString>& elements) {
    JString res;
    for (size_t i = 0; i < elements.size(); ++i) {
        if (i > 0) res += delimiter;
        res += elements[i];
    }
    return res;
}
// 未テスト
// 計算量: O(sum |args|)
template<class... Args>
inline JString jjoin(const JString& delimiter, const Args&... args) {
    vector<JString> elements{jstr(args)...};
    return jjoin(delimiter, elements);
}
inline vector<char> jchars(const JString& s) { return vector<char>(s.begin(), s.end()); }
inline char jtoUpperCase(char c) { return static_cast<char>(::toupper(static_cast<unsigned char>(c))); }
inline JString jtoUpperCase(JString s) {
    for (char& c : s) c = static_cast<char>(::toupper(static_cast<unsigned char>(c)));
    return s;
}
inline char jtoLowerCase(char c) { return static_cast<char>(::tolower(static_cast<unsigned char>(c))); }
inline JString jtoLowerCase(JString s) {
    for (char& c : s) c = static_cast<char>(::tolower(static_cast<unsigned char>(c)));
    return s;
}
inline bool jequalsIgnoreCase(const JString& a, const JString& b) {
    if (a.size() != b.size()) return false;
    for (size_t i = 0; i < a.size(); ++i) {
        if (::tolower(static_cast<unsigned char>(a[i])) != ::tolower(static_cast<unsigned char>(b[i]))) return false;
    }
    return true;
}
inline int jindexOf(const JString& s, const JString& target, int fromIndex = 0) {
    if (fromIndex < 0) fromIndex = 0;
    if ((size_t)fromIndex > s.length()) return -1;
    auto pos = s.find(target, fromIndex);
    return pos == JString::npos ? -1 : (int)pos;
}
inline int jindexOf(const JString& s, char ch, int fromIndex = 0) {
    if (fromIndex < 0) fromIndex = 0;
    if ((size_t)fromIndex > s.length()) return -1;
    auto pos = s.find(ch, fromIndex);
    return pos == JString::npos ? -1 : (int)pos;
}
inline int jlastIndexOf(const JString& s, const JString& target) {
    auto pos = s.rfind(target);
    return pos == JString::npos ? -1 : (int)pos;
}
inline int jlastIndexOf(const JString& s, const JString& target, int fromIndex) {
    if (fromIndex < 0) return -1;
    auto pos = s.rfind(target, fromIndex);
    return pos == JString::npos ? -1 : (int)pos;
}
inline int jlastIndexOf(const JString& s, char ch) {
    auto pos = s.rfind(ch);
    return pos == JString::npos ? -1 : (int)pos;
}
inline int jlastIndexOf(const JString& s, char ch, int fromIndex) {
    if (fromIndex < 0) return -1;
    auto pos = s.rfind(ch, fromIndex);
    return pos == JString::npos ? -1 : (int)pos;
}
inline JString jsubstring(const JString& s, int begin) { return s.substr(begin); }
inline JString jsubstring(const JString& s, int begin, int end) { return s.substr(begin, max(0, end - begin)); }
// 未テスト
// 計算量: O(max(0, end - begin))
inline JString jsubsequence(const JString& s, int begin, int end) { return jsubstring(s, begin, end); }
inline vector<JString> jsplit(const JString& s, const JString& regex) {
    vector<JString> result;
    std::regex re(regex);
    std::sregex_token_iterator it(s.begin(), s.end(), re, -1), end;
    for (; it != end; ++it) result.push_back(*it);
    return result;
}
inline long long jcurrentTimeMillis() {
    return chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
}
// 未テスト
// 計算量: O(1)
inline long long jnanoTime() {
    return chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count();
}
struct JDate {
    long long time_ms = 0;
    JDate() : time_ms(jcurrentTimeMillis()) {}
    explicit JDate(long long ms) : time_ms(ms) {}
    long long getTime() const { return time_ms; }
    // 未テスト
    // 計算量: O(1)
    void setTime(long long ms) { time_ms = ms; }
    // 未テスト
    // 計算量: O(1)
    bool before(const JDate& when) const { return time_ms < when.time_ms; }
    // 未テスト
    // 計算量: O(1)
    bool after(const JDate& when) const { return time_ms > when.time_ms; }
    // 未テスト
    // 計算量: O(1)
    bool equals(const JDate& o) const { return time_ms == o.time_ms; }
    // 未テスト
    // 計算量: O(1)
    int compareTo(const JDate& o) const { return (time_ms > o.time_ms) - (time_ms < o.time_ms); }
};
template<class T, class = void> struct jhas_compareTo : false_type {};
template<class T> struct jhas_compareTo<T, void_t<decltype(declval<T>().compareTo(declval<T>()))>> : true_type {};

template<class T, class = void> struct jhas_ptr_compareTo : false_type {};
template<class T> struct jhas_ptr_compareTo<T, void_t<decltype(declval<T>()->compareTo(declval<T>()))>> : true_type {};

template<class T, class = void> struct jhas_equals : false_type {};
template<class T> struct jhas_equals<T, void_t<decltype(declval<T>().equals(declval<T>()))>> : true_type {};

template<class T, class = void> struct jhas_ptr_equals : false_type {};
template<class T> struct jhas_ptr_equals<T, void_t<decltype(declval<T>()->equals(declval<T>()))>> : true_type {};

// 未テスト
// 計算量: O(1)
template<class A, class B>
bool jequals(const A& a, const B& b) {
    if constexpr (is_same_v<decay_t<A>, decay_t<B>>) {
        if constexpr (jis_std_function<decay_t<A>>::value) {
            if (!a && !b) return true;
            if (!a || !b) return false;
            return a.target_type() == b.target_type();
        } else if constexpr (jhas_ptr_equals<A>::value) {
            if (a == b) return true;
            if (a && b) return a->equals(b);
            return false;
        } else if constexpr (jhas_equals<A>::value) {
            return a.equals(b);
        } else if constexpr (jhas_ptr_compareTo<A>::value) {
            if (a == b) return true;
            if (a && b) return a->compareTo(b) == 0;
            return false;
        } else if constexpr (jhas_compareTo<A>::value) {
            return a.compareTo(b) == 0;
        } else {
            return a == b;
        }
    } else if constexpr (is_convertible_v<B, A>) {
        return a == static_cast<A>(b);
    } else if constexpr (is_convertible_v<A, B>) {
        return static_cast<B>(a) == b;
    } else {
        return false;
    }
}

template<class A, class B>
int jcompareTo(const A& a, const B& b) {
    if constexpr (jhas_ptr_compareTo<A>::value) {
        return a->compareTo(b);
    } else if constexpr (jhas_compareTo<A>::value) {
        return a.compareTo(b);
    } else {
        return (a > b) - (a < b);
    }
}

template<class F> struct JComparator {
    F key;
    template<class T> int operator()(const T& a, const T& b) const {
        if constexpr (is_invocable_v<F, const T&, const T&>) {
            return key(a, b);
        } else {
            auto x = key(a), y = key(b);
            return jcompareTo(x, y);
        }
    }
    template<class G> auto thenComparing(G other) const;
    template<class G> auto thenComparingInt(G key) const { return thenComparing(key); }
    template<class G> auto thenComparingLong(G key) const { return thenComparing(key); }
    template<class G> auto thenComparingDouble(G key) const { return thenComparing(key); }
};
template<class A, class B> struct JChainedComparator {
    A first;
    B second;
    template<class T> int operator()(const T& a, const T& b) const {
        int result = first(a, b);
        return result != 0 ? result : second(a, b);
    }
    template<class G> auto thenComparing(G other) const;
    template<class G> auto thenComparingInt(G key) const { return thenComparing(key); }
    template<class G> auto thenComparingLong(G key) const { return thenComparing(key); }
    template<class G> auto thenComparingDouble(G key) const { return thenComparing(key); }
};
template<class F> template<class G> auto JComparator<F>::thenComparing(G other) const {
    return JChainedComparator<JComparator<F>, JComparator<G>>{*this, JComparator<G>{other}};
}
template<class A, class B> template<class G> auto JChainedComparator<A, B>::thenComparing(G other) const {
    return JChainedComparator<JChainedComparator<A, B>, JComparator<G>>{*this, JComparator<G>{other}};
}
template<class T> struct jis_jcomparator : false_type {};
template<class F> struct jis_jcomparator<JComparator<F>> : true_type {};
template<class A, class B> struct jis_jcomparator<JChainedComparator<A, B>> : true_type {};

template<class F> auto jcomparing(F key) {
    if constexpr (jis_jcomparator<decay_t<F>>::value) {
        return key;
    } else {
        return JComparator<F>{key};
    }
}

// 未テスト
// 計算量: O(1)
template<class F>
auto jreversed(F cmp) {
    return [cmp = std::move(cmp)](const auto& a, const auto& b) {
        return cmp(b, a);
    };
}

// 未テスト
// 計算量: O(1)
template<class T> struct JLess {
    bool operator()(const T& a, const T& b) const {
        if constexpr (is_same_v<decay_t<T>, JObject>) {
            if (!a.has_value()) return b.has_value();
            if (!b.has_value()) return false;
            if (a.type() != b.type()) return a.type().before(b.type());
            if (auto pa = std::any_cast<int>(&a)) return *pa < std::any_cast<int>(b);
            if (auto pa = std::any_cast<long long>(&a)) return *pa < std::any_cast<long long>(b);
            if (auto pa = std::any_cast<JString>(&a)) return *pa < std::any_cast<JString>(b);
            return false;
        } else if constexpr (jhas_ptr_compareTo<T>::value) {
            return a->compareTo(b) < 0;
        } else if constexpr (jhas_compareTo<T>::value) {
            return a.compareTo(b) < 0;
        } else {
            return a < b;
        }
    }
};

struct {
    template<class A, class B>
    bool operator()(const A& a, const B& b) const {
        return JLess<decay_t<A>>{}(a, b);
    }
} jless_fn;
template<class T> void jsort(vector<T>& a) { stable_sort(a.begin(), a.end(), jless_fn); }
template<class T, class C> void jsort(vector<T>& a, C compare) {
    if constexpr (is_same_v<decay_t<C>, nullptr_t>) {
        stable_sort(a.begin(), a.end(), jless_fn);
    } else {
        using R = invoke_result_t<C, const T&, const T&>;
        stable_sort(a.begin(), a.end(), [&](const T& x, const T& y) {
            if constexpr (is_same_v<R, bool>) return compare(x, y);
            else return compare(x, y) < 0;
        });
    }
}
// 未テスト
// 計算量: O(N log N)
template<class T> void jsort(vector<T>& a, int fromIndex, int toIndex) {
    stable_sort(a.begin() + fromIndex, a.begin() + toIndex, jless_fn);
}
// 未テスト
// 計算量: O(N log N)
template<class T, class C> void jsort(vector<T>& a, int fromIndex, int toIndex, C compare) {
    if constexpr (is_same_v<decay_t<C>, nullptr_t>) {
        stable_sort(a.begin() + fromIndex, a.begin() + toIndex, jless_fn);
    } else {
        using R = invoke_result_t<C, const T&, const T&>;
        stable_sort(a.begin() + fromIndex, a.begin() + toIndex, [&](const T& x, const T& y) {
            if constexpr (is_same_v<R, bool>) return compare(x, y);
            else return compare(x, y) < 0;
        });
    }
}
// 未テスト
// 計算量: O(N)
template<class T, class U> void jfill(vector<T>& a, const U& x) {
    if constexpr (is_same_v<decay_t<U>, nullptr_t> && !is_pointer_v<T> && !is_same_v<T, JObject> && !is_same_v<T, JStringTokenizer>) {
        if constexpr (is_default_constructible_v<T>) {
            fill(a.begin(), a.end(), T{});
        } else {
            fill(a.begin(), a.end(), static_cast<T>(x));
        }
    } else {
        fill(a.begin(), a.end(), static_cast<T>(x));
    }
}
// 未テスト
// 計算量: O(toIndex - fromIndex)
template<class T, class U> void jfill(vector<T>& a, int fromIndex, int toIndex, const U& x) {
    if constexpr (is_same_v<decay_t<U>, nullptr_t> && !is_pointer_v<T> && !is_same_v<T, JObject> && !is_same_v<T, JStringTokenizer>) {
        if constexpr (is_default_constructible_v<T>) {
            fill(a.begin() + fromIndex, a.begin() + toIndex, T{});
        } else {
            fill(a.begin() + fromIndex, a.begin() + toIndex, static_cast<T>(x));
        }
    } else {
        fill(a.begin() + fromIndex, a.begin() + toIndex, static_cast<T>(x));
    }
}
template<class T> vector<T> jcopyOf(const vector<T>& a, int n) {
    vector<T> result(n);
    copy_n(a.begin(), min<int>(a.size(), n), result.begin());
    return result;
}
template<class T> vector<T> jcopyOfRange(const vector<T>& a, int from, int to) {
    vector<T> result(max(0, to - from));
    int count = max(0, min<int>(a.size(), to) - from);
    if (count > 0) copy_n(a.begin() + from, count, result.begin());
    return result;
}
template<class T> void jarraycopy(const vector<T>& src, int srcPos, vector<T>& dst, int dstPos, int length) {
    copy_n(src.begin() + srcPos, length, dst.begin() + dstPos);
}
template<class T, class F> void jsetAll(vector<T>& a, F f) {
    for (int i = 0; i < (int)a.size(); ++i) a[i] = f(i);
}
// 未テスト
// 計算量: O(N)
template<class T, class F> void jparallelSetAll(vector<T>& a, F f) { jsetAll(a, f); }

// 未テスト
// 計算量: O(min(N, M))
template<class C1, class C2> int jcompare(const C1& a, const C2& b) {
    auto it1 = a.begin(), end1 = a.end();
    auto it2 = b.begin(), end2 = b.end();
    for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
        if (*it1 < *it2) return -1;
        if (*it2 < *it1) return 1;
    }
    if (it1 != end1) return 1;
    if (it2 != end2) return -1;
    return 0;
}
// 未テスト
// 計算量: O(min(aTo - aFrom, bTo - bFrom))
template<class T> int jcompare(const vector<T>& a, int aFrom, int aTo, const vector<T>& b, int bFrom, int bTo) {
    auto it1 = a.begin() + aFrom, end1 = a.begin() + aTo;
    auto it2 = b.begin() + bFrom, end2 = b.begin() + bTo;
    for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
        if (*it1 < *it2) return -1;
        if (*it2 < *it1) return 1;
    }
    if (it1 != end1) return 1;
    if (it2 != end2) return -1;
    return 0;
}
// 未テスト
// 計算量: O(min(N, M))
template<class C1, class C2, class Comp> int jcompare(const C1& a, const C2& b, Comp comp) {
    auto it1 = a.begin(), end1 = a.end();
    auto it2 = b.begin(), end2 = b.end();
    for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
        if (comp(*it1, *it2)) return -1;
        if (comp(*it2, *it1)) return 1;
    }
    if (it1 != end1) return 1;
    if (it2 != end2) return -1;
    return 0;
}
// 未テスト
// 計算量: O(min(aTo - aFrom, bTo - bFrom))
template<class T, class Comp> int jcompare(const vector<T>& a, int aFrom, int aTo, const vector<T>& b, int bFrom, int bTo, Comp comp) {
    auto it1 = a.begin() + aFrom, end1 = a.begin() + aTo;
    auto it2 = b.begin() + bFrom, end2 = b.begin() + bTo;
    for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
        if (comp(*it1, *it2)) return -1;
        if (comp(*it2, *it1)) return 1;
    }
    if (it1 != end1) return 1;
    if (it2 != end2) return -1;
    return 0;
}

template<class T, class F> void jparallelPrefix(vector<T>& a, F op) {
    for (size_t i = 1; i < a.size(); ++i) a[i] = op(a[i - 1], a[i]);
}
template<class T, class F> void jparallelPrefix(vector<T>& a, int from, int to, F op) {
    for (int i = from + 1; i < to; ++i) a[i] = op(a[i - 1], a[i]);
}
template<class C, class T> int jbsearch(const C& a, const T& x) {
    auto it = lower_bound(a.begin(), a.end(), x);
    return it != a.end() && *it == x ? int(it - a.begin()) : -int(it - a.begin()) - 1;
}
template<class C, class T, class Comp> int jbsearch(const C& a, const T& x, Comp comp) {
    auto it = lower_bound(a.begin(), a.end(), x, comp);
    return it != a.end() && !comp(x, *it) && !comp(*it, x) ? int(it - a.begin()) : -int(it - a.begin()) - 1;
}
template<class C1, class C2> int jmismatch(const C1& a, const C2& b) {
    auto [it1, it2] = std::mismatch(a.begin(), a.end(), b.begin(), b.end());
    if (it1 == a.end() && it2 == b.end()) return -1;
    return int(distance(a.begin(), it1));
}
struct JInputStream {
    vector<char> buffer;
    size_t pos = 0;
    size_t marked_pos = 0;
    bool is_bytes = false;

    JInputStream() = default;
    JInputStream(const vector<char>& b) : buffer(b), is_bytes(true) {}
    JInputStream(const vector<int8_t>& b) : buffer(b.begin(), b.end()), is_bytes(true) {}
    template<class... Args>
    JInputStream(const JInputStream& other, Args&&...) : buffer(other.buffer), pos(other.pos), marked_pos(other.marked_pos), is_bytes(other.is_bytes) {}

    int read() {
        if (pos < buffer.size()) {
            return static_cast<unsigned char>(buffer[pos++]);
        }
        if (is_bytes) return -1;
        int ch = cin.get();
        if (ch == EOF) return -1;
        buffer.push_back(static_cast<char>(ch));
        pos++;
        return ch;
    }

    int read(vector<int8_t>& b) {
        return read(b, 0, static_cast<int>(b.size()));
    }

    int read(vector<char>& b) {
        return read(b, 0, static_cast<int>(b.size()));
    }

    template<typename T>
    int read(vector<T>& b, int off, int length) {
        int cnt = 0;
        for (int i = 0; i < length; ++i) {
            int ch = read();
            if (ch == -1) break;
            b[off + i] = static_cast<T>(ch);
            cnt++;
        }
        return cnt == 0 ? -1 : cnt;
    }

    void mark(int) {
        marked_pos = pos;
    }

    void reset() {
        pos = marked_pos;
    }

    int available() const {
        return is_bytes ? max(0, static_cast<int>(buffer.size()) - static_cast<int>(pos)) : 0;
    }

    void close() {}

    long long skip(long long n) {
        long long skipped = 0;
        while (skipped < n && read() != -1) skipped++;
        return skipped;
    }

    JString readLine() {
        JString s;
        while (true) {
            int ch = read();
            if (ch == -1) return s;
            if (ch == '\r') {
                int next_ch = read();
                if (next_ch != '\n' && next_ch != -1) {
                    // Ignore or handle non-lf after cr
                }
                break;
            }
            if (ch == '\n') break;
            s.push_back(static_cast<char>(ch));
        }
        return s;
    }
};
size_t jhash() { return 1; }
// 未テスト
// 計算量: O(1)
template<class A, class B> size_t jhashValue(const pair<A, B>& p);
template<class T, class = void> struct jhas_hash_code : false_type {};
template<class T> struct jhas_hash_code<T, void_t<decltype(declval<T>().hashCode())>> : true_type {};

template<class T, class = void> struct jhas_begin_end_range : false_type {};
template<class T> struct jhas_begin_end_range<T, void_t<decltype(declval<T>().begin()), decltype(declval<T>().end())>> : true_type {};

template<class T> size_t jhashValue(const T& x) {
    if constexpr (is_same_v<decay_t<T>, JObject>) {
        return x.has_value() ? 1 : 0;
    } else if constexpr (jis_std_function<decay_t<T>>::value) {
        return x ? 1 : 0;
    } else if constexpr (jis_nullable_val<decay_t<T>>::value || jis_optional<decay_t<T>>::value) {
        return x.has_value() ? jhashValue(*x) : 0;
    } else if constexpr (jhas_hash_code<decay_t<T>>::value) {
        return static_cast<size_t>(x.hashCode());
    } else if constexpr (jhas_begin_end_range<decay_t<T>>::value) {
        size_t result = 0;
        for (const auto& item : x) {
            result += jhashValue(item);
        }
        return result;
    } else {
        return hash<T>{}(x);
    }
}

// 未テスト
// 計算量: O(1)
template<class A, class B> size_t jhashValue(const pair<A, B>& p) {
    return jhashValue(p.first) ^ jhashValue(p.second);
}

template<class T> size_t jhashValue(const vector<T>& values) {
    size_t result = 1;
    for (const auto& value : values) result = result * 31 + jhashValue(value);
    return result;
}
template<class T, class... U> size_t jhash(const T& x, const U&... rest) {
    return jhashValue(x) * 31 + jhash(rest...);
}
inline void jnoop() {}
inline void jprint() {}
template<class T, class... U> void jprint(const T& x, const U&... rest) { cout << jstr(x); jprint(rest...); }
inline void jprintln() { cout << '\n'; }
template<class T, class... U> void jprintln(const T& x, const U&... rest) { cout << jstr(x); jprint(rest...); cout << '\n'; }
template<class... Args> void jprintf(const char* fmt, Args&&... args) {
    printf(fmt, forward<Args>(args)...);
}
template<class... Args> void jprintf(const JString& fmt, Args&&... args) {
    printf(fmt.c_str(), forward<Args>(args)...);
}

// 未テスト
// 計算量: O(1)
inline void jeprint() {}
template<class T, class... U> void jeprint(const T& x, const U&... rest) { cerr << jstr(x); jeprint(rest...); }
inline void jeprintln() { cerr << '\n'; }
template<class T, class... U> void jeprintln(const T& x, const U&... rest) { cerr << jstr(x); jeprint(rest...); cerr << '\n'; }
template<class... Args> void jeprintf(const char* fmt, Args&&... args) {
    fprintf(stderr, fmt, forward<Args>(args)...);
}
template<class... Args> void jeprintf(const JString& fmt, Args&&... args) {
    fprintf(stderr, fmt.c_str(), forward<Args>(args)...);
}

template<class... Args> JString jformat(const char* fmt, Args&&... args) {
    int sz = snprintf(nullptr, 0, fmt, forward<Args>(args)...);
    if (sz <= 0) return "";
    vector<char> buf(sz + 1);
    snprintf(buf.data(), buf.size(), fmt, forward<Args>(args)...);
    return JString(buf.data(), sz);
}
template<class... Args> JString jformat(const JString& fmt, Args&&... args) {
    return jformat(fmt.c_str(), forward<Args>(args)...);
}
template<class L, class... Args>
typename enable_if<!is_convertible_v<L, JString> && !is_convertible_v<L, const char*>, JString>::type
jformat(const L&, const char* fmt, Args&&... args) {
    return jformat(fmt, forward<Args>(args)...);
}
template<class L, class... Args>
typename enable_if<!is_convertible_v<L, JString> && !is_convertible_v<L, const char*>, JString>::type
jformat(const L&, const JString& fmt, Args&&... args) {
    return jformat(fmt.c_str(), forward<Args>(args)...);
}
template<class T> auto jsignum(T x) {
    if constexpr (std::is_floating_point_v<T>) {
        if (std::isnan(x)) return x;
        return x > T(0) ? T(1) : (x < T(0) ? T(-1) : T(0));
    } else {
        return (x > T(0)) - (x < T(0));
    }
}
template<class A, class B> auto jmin(const A& a, const B& b) {
    using C = common_type_t<A, B>;
    if constexpr (std::is_floating_point_v<C>) {
        if (std::isnan(a) || std::isnan(b)) return std::numeric_limits<C>::quiet_NaN();
    }
    return std::min<C>(a, b);
}
template<class A, class B> auto jmax(const A& a, const B& b) {
    using C = common_type_t<A, B>;
    if constexpr (std::is_floating_point_v<C>) {
        if (std::isnan(a) || std::isnan(b)) return std::numeric_limits<C>::quiet_NaN();
    }
    return std::max<C>(a, b);
}
// 未テスト
// 計算量: O(1)
template<class T> auto jround(T x) {
    if constexpr (std::is_same_v<decay_t<T>, float>) {
        return static_cast<int>(std::floor(x + 0.5f));
    } else {
        return static_cast<long long>(std::floor(x + 0.5));
    }
}

template<class A, class B> auto jfloorDiv(A a, B b) {
    using C = common_type_t<A, B>;
    C x = a, y = b;
    C res = x / y;
    C rem = x % y;
    if ((rem != 0) && ((x ^ y) < 0)) --res;
    return res;
}
template<class A, class B> auto jceilDiv(A a, B b) {
    using C = common_type_t<A, B>;
    C x = a, y = b;
    C res = x / y;
    C rem = x % y;
    if ((rem != 0) && ((x ^ y) > 0)) ++res;
    return res;
}
template<class A, class B> auto jfloorMod(A a, B b) {
    using C = common_type_t<A, B>;
    C x = a, y = b;
    C rem = x % y;
    if ((rem != 0) && ((x ^ y) < 0)) rem += y;
    return rem;
}
// 未テスト
// 計算量: O(1)
template<class T, class U>
auto jusr(T a, U b) {
    using UT = std::make_unsigned_t<T>;
    return static_cast<T>(static_cast<UT>(a) >> b);
}

template<class V, class L, class H> auto jclamp(V v, L l, H h) {
    return v < l ? l : (v > h ? h : v);
}
template<class A, class B> auto jaddExact(A a, B b) { return a + b; }
template<class A, class B> auto jsubtractExact(A a, B b) { return a - b; }
template<class A, class B> auto jmultiplyExact(A a, B b) { return a * b; }
template<class T> auto jtoIntExact(T x) { return static_cast<int>(x); }
template<class T> auto jnegateExact(T x) { return -x; }
// 未テスト
// 計算量: O(1)
template<class T> auto jabsExact(T x) { return x < 0 ? -x : x; }
// 未テスト
// 計算量: O(1)
template<class T> auto jincrementExact(T a) { return a + 1; }
// 未テスト
// 計算量: O(1)
template<class T> auto jdecrementExact(T a) { return a - 1; }
// 未テスト
// 計算量: O(1)
inline long long jmultiplyFull(int x, int y) { return static_cast<long long>(x) * y; }
// 未テスト
// 計算量: O(1)
inline long long jmultiplyHigh(long long x, long long y) {
    return static_cast<long long>((static_cast<__int128>(x) * static_cast<__int128>(y)) >> 64);
}
// 未テスト
// 計算量: O(1)
inline double jtoRadians(double angdeg) { return angdeg * 3.14159265358979323846 / 180.0; }
// 未テスト
// 計算量: O(1)
inline double jtoDegrees(double angrad) { return angrad * 180.0 / 3.14159265358979323846; }

template<class A, class B> int jcompareValue(const A& a, const B& b) {
    return (a > b) - (a < b);
}
template<class T> int jcompare(const vector<T>& a, const vector<T>& b) {
    if (lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) return -1;
    if (lexicographical_compare(b.begin(), b.end(), a.begin(), a.end())) return 1;
    return 0;
}
template<class T> struct JOptional {
    bool has = false;
    T val = {};
    bool isPresent() const { return has; }
    // 未テスト
    // 計算量: O(1)
    bool isEmpty() const { return !has; }
    T get() const { return val; }
    long long getAsLong() const { return static_cast<long long>(val); }
    int getAsInt() const { return static_cast<int>(val); }
    double getAsDouble() const { return static_cast<double>(val); }
    T orElse(T def) const { return has ? val : def; }
    // 未テスト
    // 計算量: O(1)
    template<class F> T orElseGet(F supplier) const { return has ? val : supplier(); }
    // 未テスト
    // 計算量: O(1)
    T orElseThrow() const {
        if (!has) throw runtime_error("No value present");
        return val;
    }
    // 未テスト
    // 計算量: O(1)
    template<class F> void ifPresent(F action) const {
        if (has) action(val);
    }
    // 未テスト
    // 計算量: O(f)
    // map: JOptional<T> x (T -> U) -> JOptional<U>
    template<class F> auto map(F f) const -> JOptional<decltype(f(val))> {
        if (!has) return JOptional<decltype(f(val))>{false, {}};
        return JOptional<decltype(f(val))>{true, f(val)};
    }
    // 未テスト
    // 計算量: O(f)
    // flatMap: JOptional<T> x (T -> JOptional<U>) -> JOptional<U>
    template<class F> auto flatMap(F f) const -> decltype(f(val)) {
        if (!has) return decltype(f(val)){false, {}};
        return f(val);
    }
};

// 任意の JOptional<T> へ暗黙変換できる空値センチネル型。
// 計算量: O(1)
struct JOptionalEmpty {
    template<class T> operator JOptional<T>() const { return JOptional<T>{false, {}}; }
};

struct Optional {
    // 未テスト
    // 計算量: O(1)
    template<class T> static JOptional<T> of(T v) { return JOptional<T>{true, v}; }
    // 未テスト
    // 計算量: O(1)
    template<class T> static JOptional<T> ofNullable(T v) { return JOptional<T>{!jisNull(v), v}; }
    // 未テスト
    // 計算量: O(1)
    // empty() は任意の JOptional<T> へ暗黙変換できる JOptionalEmpty を返す。
    static JOptionalEmpty empty() { return JOptionalEmpty{}; }
};

struct OptionalLong {
    // 未テスト
    // 計算量: O(1)
    static JOptional<long long> of(long long v) { return JOptional<long long>{true, v}; }
    // 未テスト
    // 計算量: O(1)
    static JOptionalEmpty empty() { return JOptionalEmpty{}; }
};

struct OptionalInt {
    // 未テスト
    // 計算量: O(1)
    static JOptional<int> of(int v) { return JOptional<int>{true, v}; }
    // 未テスト
    // 計算量: O(1)
    static JOptionalEmpty empty() { return JOptionalEmpty{}; }
};

struct OptionalDouble {
    // 未テスト
    // 計算量: O(1)
    static JOptional<double> of(double v) { return JOptional<double>{true, v}; }
    // 未テスト
    // 計算量: O(1)
    static JOptionalEmpty empty() { return JOptionalEmpty{}; }
};
template<class T> struct JStream;
inline vector<JObject> jlistOf() { return {}; }
template<class T> auto jlistOf(const vector<T>& v) { return v; }
template<class T, class... U> auto jlistOf(T first, U... rest) {
    using V = common_type_t<T, U...>;
    return vector<V>{static_cast<V>(first), static_cast<V>(rest)...};
}

template<class T> struct JList : vector<T> {
    JList() = default;
    explicit JList(size_t initialCapacity) { this->reserve(initialCapacity); }
    JList(size_t count, const T& value) : vector<T>(count, value) {}
    JList(const vector<T>& source) : vector<T>(source) {}
    JList(vector<T>&& source) : vector<T>(move(source)) {}
    template<class U> JList(const JList<U>& source) {
        for (const auto& value : source) {
            if constexpr (is_same_v<U, JObject>) this->push_back(any_cast<T>(value));
            else this->push_back(static_cast<T>(value));
        }
    }
    template<class Iter, class = typename std::iterator_traits<Iter>::value_type>
    JList(Iter first, Iter last) : vector<T>(first, last) {}
    template<class Container, class = enable_if_t<!is_convertible_v<Container, std::size_t> && !is_same_v<decay_t<Container>, JList> && !is_same_v<decay_t<Container>, vector<T>>>>
    JList(const Container& container) {
        for (const auto& item : container) {
            if constexpr (is_same_v<decay_t<decltype(item)>, JObject>) this->push_back(any_cast<T>(item));
            else this->push_back(item);
        }
    }
    bool add(const T& x) { this->push_back(x); return true; }
    void add(int i, const T& x) { this->insert(this->begin() + i, x); }
    // 未テスト
    // 計算量: O(N)
    void addFirst(const T& x) { this->insert(this->begin(), x); }
    // 未テスト
    // 計算量: O(1)
    void addLast(const T& x) { this->push_back(x); }
    // 未テスト
    // 計算量: O(1)
    T getFirst() const { return this->front(); }
    // 未テスト
    // 計算量: O(1)
    T getLast() const { return this->back(); }
    T get(int i) const { return (*this)[i]; }
    T set(int i, const T& x) { T old = (*this)[i]; (*this)[i] = x; return old; }
    int size() const { return (int)vector<T>::size(); }
    bool isEmpty() const { return this->empty(); }
    T remove(int index) {
        T old = (*this)[index];
        this->erase(this->begin() + index);
        return old;
    }
    // 未テスト
    // 計算量: O(N)
    T removeFirst() {
        T old = this->front();
        this->erase(this->begin());
        return old;
    }
    // 未テスト
    // 計算量: O(1)
    T removeLast() {
        T old = this->back();
        this->pop_back();
        return old;
    }
    template<class Arg>
    bool remove(const Arg& x) {
        if constexpr (is_integral_v<Arg> && !is_same_v<decay_t<Arg>, bool>) {
            if constexpr (is_integral_v<T> && !is_same_v<decay_t<T>, bool>) {
                auto it = std::find(this->begin(), this->end(), static_cast<T>(x));
                if (it != this->end()) { this->erase(it); return true; }
                return false;
            } else {
                auto it = std::find_if(this->begin(), this->end(), [&](const T& item) {
                    if constexpr (is_convertible_v<Arg, T>) return jequals(item, x);
                    else if constexpr (jhas_key<T>::value) return item->key == x;
                    else if constexpr (jhas_key_obj<T>::value) return item.key == x;
                    else return false;
                });
                if (it != this->end()) { this->erase(it); return true; }
                return false;
            }
        } else {
            auto it = std::find_if(this->begin(), this->end(), [&](const T& item) {
                if constexpr (is_convertible_v<Arg, T>) return jequals(item, x);
                else if constexpr (jhas_key<T>::value) return item->key == x;
                else if constexpr (jhas_key_obj<T>::value) return item.key == x;
                else return false;
            });
            if (it != this->end()) { this->erase(it); return true; }
            return false;
        }
    }
    template<class C> bool addAll(const C& c) {
        for (const auto& x : c) this->push_back(x);
        return true;
    }
    // 未テスト
    // 計算量: O(N + M)
    template<class C> bool addAll(int index, const C& c) {
        if (index < 0 || index > (int)this->size()) return false;
        size_t pos = index;
        for (const auto& x : c) {
            this->insert(this->begin() + pos, x);
            ++pos;
        }
        return true;
    }
    // 未テスト
    // 計算量: O(N * M)
    template<class C> bool removeAll(const C& c) {
        bool modified = false;
        for (auto it = this->begin(); it != this->end(); ) {
            bool found = false;
            for (const auto& x : c) {
                if (jequals(*it, x)) { found = true; break; }
            }
            if (found) { it = this->erase(it); modified = true; }
            else { ++it; }
        }
        return modified;
    }
    // 未テスト
    // 計算量: O(N * M)
    template<class C> bool retainAll(const C& c) {
        bool modified = false;
        for (auto it = this->begin(); it != this->end(); ) {
            bool found = false;
            for (const auto& x : c) {
                if (jequals(*it, x)) { found = true; break; }
            }
            if (!found) { it = this->erase(it); modified = true; }
            else { ++it; }
        }
        return modified;
    }
    // 未テスト
    // 計算量: O(N * M)
    template<class C> bool containsAll(const C& c) const {
        for (const auto& x : c) {
            if (!this->contains(x)) return false;
        }
        return true;
    }
    // 未テスト
    // 計算量: O(N)
    template<class F> void replaceAll(F operator_fn) {
        for (auto& item : *this) item = operator_fn(item);
    }
    template<class Arg>
    bool contains(const Arg& x) const {
        return std::find_if(this->begin(), this->end(), [&](const T& item) {
            return jequals(item, x);
        }) != this->end();
    }
    template<class Arg = T>
    int indexOf(const Arg& x) const {
        auto it = std::find_if(this->begin(), this->end(), [&](const T& item) {
            return jequals(item, x);
        });
        return it == this->end() ? -1 : (int)distance(this->begin(), it);
    }
    template<class Arg = T>
    int lastIndexOf(const Arg& x) const {
        auto it = std::find_if(this->rbegin(), this->rend(), [&](const T& item) {
            return jequals(item, x);
        });
        return it == this->rend() ? -1 : (int)(this->size() - 1 - distance(this->rbegin(), it));
    }
    template<class Comp> void sort(Comp comp) {
        if constexpr (is_same_v<decay_t<Comp>, nullptr_t>) {
            std::stable_sort(this->begin(), this->end(), jless_fn);
        } else {
            using R = invoke_result_t<Comp, const T&, const T&>;
            std::stable_sort(this->begin(), this->end(), [&](const auto& a, const auto& b) {
                if constexpr (is_same_v<R, bool>) return comp(a, b);
                else return comp(a, b) < 0;
            });
        }
    }
    void sort(nullptr_t) {
        std::stable_sort(this->begin(), this->end(), jless_fn);
    }
    void sort() {
        std::stable_sort(this->begin(), this->end(), jless_fn);
    }
    JList<T> subList(int fromIndex, int toIndex) const {
        if (fromIndex < 0) fromIndex = 0;
        if (toIndex > (int)this->size()) toIndex = (int)this->size();
        if (fromIndex >= toIndex) return JList<T>{};
        return JList<T>(this->begin() + fromIndex, this->begin() + toIndex);
    }
    auto stream() const { return JStream<T>(*this); }
};
template<class P, class = void> struct jhas_next : false_type {};
template<class P> struct jhas_next<P, void_t<decltype(declval<P>()->next())>> : true_type {};

template<class P, class = void> struct jhas_nextInt : false_type {};
template<class P> struct jhas_nextInt<P, void_t<decltype(declval<P>()->nextInt())>> : true_type {};

template<class P, class = void> struct jhas_nextLong : false_type {};
template<class P> struct jhas_nextLong<P, void_t<decltype(declval<P>()->nextLong())>> : true_type {};

template<class P, class = void> struct jhas_nextDouble : false_type {};
template<class P> struct jhas_nextDouble<P, void_t<decltype(declval<P>()->nextDouble())>> : true_type {};

// 未テスト
// 計算量: O(1)
template<class C, class = void> struct jhas_iterator : false_type {};
template<class C> struct jhas_iterator<C, void_t<decltype(declval<C>().iterator())>> : true_type {};

// 未テスト
// 計算量: O(1)
template<class C, class = void> struct jhas_ptr_iterator : false_type {};
template<class C> struct jhas_ptr_iterator<C, void_t<decltype(declval<C>()->iterator())>> : true_type {};

// 未テスト
// 計算量: O(1)
template<class C, class = void> struct jhas_begin_end : false_type {};
template<class C> struct jhas_begin_end<C, void_t<decltype(declval<C>().begin()), decltype(declval<C>().end())>> : true_type {};

// 未テスト
// 計算量: O(1)
template<class C, class = void> struct jhas_ptr_begin_end : false_type {};
template<class C> struct jhas_ptr_begin_end<C, void_t<decltype(declval<C>()->begin()), decltype(declval<C>()->end())>> : true_type {};

template<class T> struct JIterable;

template<class T> struct JIterator {
    function<bool()> fn_hasNext;
    function<T()> fn_next;
    vector<T> items;
    size_t pos = 0;
    bool valid = false;

    JIterator() = default;
    JIterator(const vector<T>& v) : items(v), valid(true) {}
    JIterator(const JIterable<T>& it);

    template<class Ptr, class = enable_if_t<!is_same_v<decay_t<Ptr>, vector<T>> && !is_same_v<decay_t<Ptr>, JIterator> && !is_same_v<decay_t<Ptr>, JIterable<T>>>>
    JIterator(Ptr ptr) {
        if constexpr (jhas_iterator<decay_t<Ptr>>::value) {
            *this = ptr.iterator();
        } else if constexpr (jhas_ptr_iterator<decay_t<Ptr>>::value) {
            if (ptr) *this = ptr->iterator();
        } else if constexpr (jhas_begin_end<decay_t<Ptr>>::value) {
            items.assign(ptr.begin(), ptr.end());
            valid = true;
        } else if constexpr (jhas_ptr_begin_end<decay_t<Ptr>>::value) {
            if (ptr) {
                items.assign(ptr->begin(), ptr->end());
                valid = true;
            }
        } else {
            valid = bool(ptr);
            if (ptr) {
                fn_hasNext = [ptr]() { return ptr->hasNext(); };
                fn_next = [ptr]() {
                    if constexpr (jhas_next<Ptr>::value) {
                        return ptr->next();
                    } else if constexpr (jhas_nextInt<Ptr>::value) {
                        return ptr->nextInt();
                    } else if constexpr (jhas_nextLong<Ptr>::value) {
                        return ptr->nextLong();
                    } else if constexpr (jhas_nextDouble<Ptr>::value) {
                        return ptr->nextDouble();
                    } else {
                        return T{};
                    }
                };
            }
        }
    }
    virtual bool hasNext() {
        if (fn_hasNext) return fn_hasNext();
        return pos < items.size();
    }
    virtual T next() {
        if (fn_next) return fn_next();
        return items[pos++];
    }
    virtual int nextInt() {
        if constexpr (is_convertible_v<T, int>) return static_cast<int>(next());
        else return 0;
    }
    virtual long long nextLong() {
        if constexpr (is_convertible_v<T, long long>) return static_cast<long long>(next());
        else return 0;
    }
    virtual double nextDouble() {
        if constexpr (is_convertible_v<T, double>) return static_cast<double>(next());
        else return 0.0;
    }
    bool operator==(nullptr_t) const { return !valid && !fn_hasNext; }
    bool operator!=(nullptr_t) const { return valid || bool(fn_hasNext); }
};

template<class T> struct JIterable {
    function<JIterator<T>()> supplier;
    JIterable() = default;
    template<class F, class = enable_if_t<!is_same_v<decay_t<F>, vector<T>> && !is_same_v<decay_t<F>, JIterable>>>
    JIterable(F f) {
        if constexpr (jhas_iterator<decay_t<F>>::value) {
            supplier = [f]() -> JIterator<T> {
                return f.iterator();
            };
        } else if constexpr (jhas_ptr_iterator<decay_t<F>>::value) {
            supplier = [f]() -> JIterator<T> {
                return f ? f->iterator() : JIterator<T>();
            };
        } else if constexpr (jhas_begin_end<decay_t<F>>::value) {
            supplier = [f]() -> JIterator<T> {
                vector<T> v;
                for (auto it = f.begin(); it != f.end(); ++it) v.push_back(*it);
                return JIterator<T>(v);
            };
        } else if constexpr (jhas_ptr_begin_end<decay_t<F>>::value) {
            supplier = [f]() -> JIterator<T> {
                if (!f) return JIterator<T>();
                vector<T> v;
                for (auto it = f->begin(); it != f->end(); ++it) v.push_back(*it);
                return JIterator<T>(v);
            };
        } else {
            supplier = [f]() -> JIterator<T> {
                return JIterator<T>(f());
            };
        }
    }
    JIterable(const vector<T>& v) : supplier([v]() { return JIterator<T>(v); }) {}
    JIterator<T> iterator() const { return supplier ? supplier() : JIterator<T>(); }
    struct CppIterator {
        JIterator<T> it;
        optional<T> current_val;
        CppIterator() = default;
        explicit CppIterator(JIterator<T> iter) : it(iter) {
            if (it.hasNext()) current_val = it.next();
        }
        bool operator!=(const CppIterator&) const { return current_val.has_value(); }
        void operator++() {
            if (it.hasNext()) current_val = it.next();
            else current_val.reset();
        }
        T operator*() const { return *current_val; }
    };
    CppIterator begin() { return CppIterator(this->iterator()); }
    CppIterator end() { return CppIterator(); }
    CppIterator begin() const { return CppIterator(iterator()); }
    CppIterator end() const { return CppIterator(); }
};

template<class T>
inline JIterator<T>::JIterator(const JIterable<T>& it) : valid(bool(it.supplier)) {
    *this = it.iterator();
}

template<class T> JIterator(const JIterable<T>&) -> JIterator<T>;

template<class C, class = void> struct jcontainer_value_type { using type = void; };
template<class C> struct jcontainer_value_type<C, void_t<typename C::value_type>> { using type = typename C::value_type; };

template<class C> JIterator(const C&) -> JIterator<typename jcontainer_value_type<decay_t<C>>::type>;
struct JArray {
    template<class T = JObject>
    static vector<T> newInstance(const std::type_info&, int length) {
        return vector<T>(length);
    }
    template<class T>
    static vector<T> newInstance(const T&, int length) {
        return vector<T>(length);
    }
    template<class T> static int getLength(const vector<T>& v) { return static_cast<int>(v.size()); }
    static int getLength(const JObject& obj) {
        if (!obj.has_value()) return 0;
        try { return static_cast<int>(std::any_cast<vector<int>>(obj).size()); } catch(...) {}
        try { return static_cast<int>(std::any_cast<vector<long long>>(obj).size()); } catch(...) {}
        try { return static_cast<int>(std::any_cast<vector<JObject>>(obj).size()); } catch(...) {}
        return 0;
    }
    template<class T> static auto get(const vector<T>& v, int index) { return v[index]; }
    static JObject get(const JObject& obj, int index) {
        try { return std::any_cast<vector<int>>(obj)[index]; } catch(...) {}
        try { return std::any_cast<vector<long long>>(obj)[index]; } catch(...) {}
        try { return std::any_cast<vector<JObject>>(obj)[index]; } catch(...) {}
        return {};
    }
};
using Array = JArray;

template<class C> auto jtoArray(const C& values) {
    using T = typename C::value_type;
    return vector<T>(values.begin(), values.end());
}
template<class T> struct JPriorityQueue {
    function<int(const T&, const T&)> comp = [](const T& a, const T& b) { return jcompareTo(a, b); };
    vector<T> data;

    void siftUp(size_t k, T x) {
        while (k > 0) {
            size_t parent = (k - 1) / 2;
            const T& e = data[parent];
            if (comp(x, e) >= 0) break;
            data[k] = std::move(data[parent]);
            k = parent;
        }
        data[k] = std::move(x);
    }

    void siftDown(size_t k, T x) {
        size_t half = data.size() / 2;
        while (k < half) {
            size_t child = (k * 2) + 1;
            size_t right = child + 1;
            if (right < data.size() && comp(data[child], data[right]) > 0) {
                child = right;
            }
            if (comp(x, data[child]) <= 0) break;
            data[k] = std::move(data[child]);
            k = child;
        }
        data[k] = std::move(x);
    }

    void heapify() {
        if (data.size() <= 1) return;
        for (int i = (static_cast<int>(data.size()) / 2) - 1; i >= 0; --i) {
            T item = std::move(data[i]);
            siftDown(static_cast<size_t>(i), std::move(item));
        }
    }

    JPriorityQueue() = default;
    template<class C, class = enable_if_t<is_invocable_v<C, const T&, const T&>>>
    explicit JPriorityQueue(C c) : comp([c](const T& a, const T& b) { return c(a, b); }) {}
    template<class C, class = enable_if_t<is_invocable_v<C, const T&, const T&>>>
    JPriorityQueue(int, C c) : comp([c](const T& a, const T& b) { return c(a, b); }) {}
    explicit JPriorityQueue(int) {}
    // 未テスト
    // 計算量: O(|c|)
    template<class Container, class = enable_if_t<!is_convertible_v<Container, std::size_t> && !is_same_v<decay_t<Container>, JPriorityQueue> && !is_invocable_v<Container, const T&, const T&>>>
    explicit JPriorityQueue(const Container& c) {
        for (const auto& item : c) {
            if constexpr (is_same_v<decay_t<decltype(item)>, JObject>) data.push_back(any_cast<T>(item));
            else data.push_back(item);
        }
        heapify();
    }

    bool add(const T& x) {
        size_t i = data.size();
        data.push_back(x);
        siftUp(i, x);
        return true;
    }
    // 未テスト
    // 計算量: O(|c| log N)
    template<class Container> bool addAll(const Container& c) {
        for (const auto& item : c) add(item);
        return true;
    }
    bool offer(const T& x) { return add(x); }
    T poll() {
        if (data.empty()) return T{};
        T result = std::move(data[0]);
        T last = std::move(data.back());
        data.pop_back();
        if (!data.empty()) {
            siftDown(0, std::move(last));
        }
        return result;
    }
    T peek() const { return data.empty() ? T{} : data[0]; }
    // 未テスト
    // 計算量: O(1)
    T& peek() { return data[0]; }
    int size() const { return (int)data.size(); }
    bool isEmpty() const { return data.empty(); }
    bool empty() const { return data.empty(); }
    void clear() { data.clear(); }
    // 未テスト
    // 計算量: O(1)
    auto begin() const { return data.begin(); }
    // 未テスト
    // 計算量: O(1)
    auto end() const { return data.end(); }
    // 未テスト
    // 計算量: O(1)
    auto begin() { return data.begin(); }
    // 未テスト
    // 計算量: O(1)
    auto end() { return data.end(); }

    template<class Arg>
    bool remove(const Arg& x) {
        for (size_t i = 0; i < data.size(); ++i) {
            if (jequals(data[i], x)) {
                T last = std::move(data.back());
                data.pop_back();
                if (i < data.size()) {
                    siftDown(i, last);
                    if (jequals(data[i], last)) {
                        siftUp(i, std::move(last));
                    }
                }
                return true;
            }
        }
        return false;
    }
};
struct System {
    static void gc() {}
    // 未テスト
    // 計算量: O(1)
    static long long currentTimeMillis() { return jcurrentTimeMillis(); }
    // 未テスト
    // 計算量: O(1)
    static long long nanoTime() { return jnanoTime(); }
    // 未テスト
    // 計算量: O(1)
    static void exit(int status) { ::exit(status); }
    // 未テスト
    // 計算量: O(length)
    template<class Src, class Dest>
    static void arraycopy(const Src& src, int srcPos, Dest& dest, int destPos, int length) {
        jarraycopy(src, srcPos, dest, destPos, length);
    }
};
struct JInputStream;
// 未テスト
// 計算量: O(1)
struct JPrintWriter {
    bool is_err = false;
    JPrintWriter() = default;
    explicit JPrintWriter(bool err) : is_err(err) {}
    template<class StreamType, class = enable_if_t<is_same_v<decay_t<StreamType>, JInputStream>>> explicit JPrintWriter(const StreamType&) {}
    explicit JPrintWriter(nullptr_t) {}
    template<class T> void print(const T& x) { if (is_err) jeprint(x); else jprint(x); }
    template<class T> void println(const T& x) { if (is_err) jeprintln(x); else jprintln(x); }
    template<class T> void print(const vector<T>& a) { print(a, " "); }
    template<class T> void println(const vector<T>& a) { println(a, " "); }
    void print(const vector<char>& a) { for (char c : a) print(c); }
    void println(const vector<char>& a) { for (char c : a) print(c); println(); }
    template<class T> void print(const vector<T>& a, const JString& separator) {
        for (size_t i = 0; i < a.size(); ++i) { if (i) print(separator); print(a[i]); }
    }
    template<class T> void println(const vector<T>& a, const JString& separator) {
        for (size_t i = 0; i < a.size(); ++i) { if (i) print(separator); print(a[i]); }
        println();
    }
    void println() { if (is_err) jeprintln(); else jprintln(); }
    void printlnYesNo(bool x) { println(x ? "Yes" : "No"); }
    template<class... Args> void printf(Args&&... args) { if (is_err) jeprintf(forward<Args>(args)...); else jprintf(forward<Args>(args)...); }
    template<class T> void write(const T& x) { print(x); }
    void write(int c) { if (is_err) cerr.put(static_cast<char>(c)); else cout.put(static_cast<char>(c)); }
    void write(const JString& s, int off, int len) { if (is_err) cerr << s.substr(off, len); else cout << s.substr(off, len); }
    void flush() { if (is_err) cerr.flush(); else cout.flush(); }
    void close() { flush(); }
};
struct JLong {
    static constexpr long long MAX_VALUE = numeric_limits<long long>::max();
    static constexpr long long MIN_VALUE = numeric_limits<long long>::min();
    static constexpr int BYTES = 8;
    static constexpr int SIZE = 64;
    static int compare(long long a, long long b) { return (a > b) - (a < b); }
    static int hashCode(long long x) { return static_cast<int>(x ^ (x >> 32)); }
    static int signum(long long x) { return (x > 0) - (x < 0); }
    static long long sum(long long a, long long b) { return a + b; }
    static long long max(long long a, long long b) { return std::max(a, b); }
    static long long min(long long a, long long b) { return std::min(a, b); }
    static int bitCount(long long x) { return __builtin_popcountll(static_cast<unsigned long long>(x)); }
    static int numberOfLeadingZeros(long long x) { return x ? __builtin_clzll((unsigned long long)x) : 64; }
    static int numberOfTrailingZeros(long long x) { return x ? __builtin_ctzll((unsigned long long)x) : 64; }
    static long long highestOneBit(long long x) { return x ? (1ULL << (63 - __builtin_clzll(static_cast<unsigned long long>(x)))) : 0LL; }
    static long long lowestOneBit(long long x) { return x & -x; }
    // 未テスト
    // 計算量: O(1)
    static long long rotateLeft(long long i, int distance) {
        uint64_t u = static_cast<uint64_t>(i);
        int dist = distance & 63;
        return static_cast<long long>((u << dist) | (u >> ((64 - dist) & 63)));
    }
    // 未テスト
    // 計算量: O(1)
    static long long rotateRight(long long i, int distance) {
        uint64_t u = static_cast<uint64_t>(i);
        int dist = distance & 63;
        return static_cast<long long>((u >> dist) | (u << ((64 - dist) & 63)));
    }
    // 未テスト
    // 計算量: O(1)
    static long long divideUnsigned(long long dividend, long long divisor) {
        return static_cast<long long>(static_cast<uint64_t>(dividend) / static_cast<uint64_t>(divisor));
    }
    // 未テスト
    // 計算量: O(1)
    static long long remainderUnsigned(long long dividend, long long divisor) {
        return static_cast<long long>(static_cast<uint64_t>(dividend) % static_cast<uint64_t>(divisor));
    }
    // 未テスト
    // 計算量: O(1)
    static int compareUnsigned(long long x, long long y) {
        uint64_t ux = static_cast<uint64_t>(x);
        uint64_t uy = static_cast<uint64_t>(y);
        return (ux > uy) - (ux < uy);
    }
    static long long reverse(long long x) {
        uint64_t u = static_cast<uint64_t>(x);
        u = ((u & 0x5555555555555555ULL) << 1) | ((u & 0xAAAAAAAAAAAAAAAAULL) >> 1);
        u = ((u & 0x3333333333333333ULL) << 2) | ((u & 0xCCCCCCCCCCCCCCCCULL) >> 2);
        u = ((u & 0x0F0F0F0F0F0F0F0FULL) << 4) | ((u & 0xF0F0F0F0F0F0F0F0ULL) >> 4);
        u = ((u & 0x00FF00FF00FF00FFULL) << 8) | ((u & 0xFF00FF00FF00FF00ULL) >> 8);
        u = ((u & 0x0000FFFF0000FFFFULL) << 16) | ((u & 0xFFFF0000FFFF0000ULL) >> 16);
        u = (u << 32) | (u >> 32);
        return static_cast<long long>(u);
    }
    static long long reverseBytes(long long x) {
        return static_cast<long long>(__builtin_bswap64(static_cast<uint64_t>(x)));
    }
    static JString toBinaryString(long long x) {
        if (x == 0) return "0";
        uint64_t u = static_cast<uint64_t>(x);
        string s;
        while (u > 0) {
            s.push_back((u & 1) ? '1' : '0');
            u >>= 1;
        }
        std::reverse(s.begin(), s.end());
        return s;
    }
    static JString toHexString(long long x) {
        if (x == 0) return "0";
        uint64_t u = static_cast<uint64_t>(x);
        stringstream ss;
        ss << std::hex << u;
        return ss.str();
    }
    static JString toOctalString(long long x) {
        if (x == 0) return "0";
        uint64_t u = static_cast<uint64_t>(x);
        stringstream ss;
        ss << std::oct << u;
        return ss.str();
    }
    static JString toUnsignedString(long long x, int radix = 10) {
        if (x == 0) return "0";
        uint64_t u = static_cast<uint64_t>(x);
        if (radix == 10) return std::to_string(u);
        if (radix == 2) return toBinaryString(x);
        if (radix == 16) return toHexString(x);
        if (radix == 8) return toOctalString(x);
        return std::to_string(u);
    }
    static JString toString(long long x, int radix = 10) {
        if (radix == 10) return std::to_string(x);
        if (radix == 2) return toBinaryString(x);
        if (radix == 16) return toHexString(x);
        if (radix == 8) return toOctalString(x);
        return std::to_string(x);
    }
    static long long parseLong(const JString& x, int radix = 10) { return stoll(x, nullptr, radix); }
    // 未テスト
    // 計算量: O(|x|)
    static long long parseUnsignedLong(const JString& x, int radix = 10) { return static_cast<long long>(stoull(x, nullptr, radix)); }
    static long long valueOf(const JString& x, int radix = 10) { return stoll(x, nullptr, radix); }
    static long long valueOf(long long x) { return x; }
};
struct JInteger {
    static constexpr int MAX_VALUE = numeric_limits<int>::max();
    static constexpr int MIN_VALUE = numeric_limits<int>::min();
    static constexpr int BYTES = 4;
    static constexpr int SIZE = 32;
    static int compare(int a, int b) { return (a > b) - (a < b); }
    static int hashCode(int x) { return x; }
    static int signum(int x) { return (x > 0) - (x < 0); }
    static int sum(int a, int b) { return a + b; }
    static int max(int a, int b) { return std::max(a, b); }
    static int min(int a, int b) { return std::min(a, b); }
    static int bitCount(int x) { return __builtin_popcount((unsigned int)x); }
    static int numberOfLeadingZeros(int x) { return x ? __builtin_clz((unsigned int)x) : 32; }
    static int numberOfTrailingZeros(int x) { return x ? __builtin_ctz((unsigned int)x) : 32; }
    static int highestOneBit(int x) { return x ? int(1U << (31 - __builtin_clz((unsigned int)x))) : 0; }
    static int lowestOneBit(int x) { return x & -x; }
    // 未テスト
    // 計算量: O(1)
    static int rotateLeft(int i, int distance) {
        uint32_t u = static_cast<uint32_t>(i);
        int dist = distance & 31;
        return static_cast<int>((u << dist) | (u >> ((32 - dist) & 31)));
    }
    // 未テスト
    // 計算量: O(1)
    static int rotateRight(int i, int distance) {
        uint32_t u = static_cast<uint32_t>(i);
        int dist = distance & 31;
        return static_cast<int>((u >> dist) | (u << ((32 - dist) & 31)));
    }
    // 未テスト
    // 計算量: O(1)
    static int divideUnsigned(int dividend, int divisor) {
        return static_cast<int>(static_cast<uint32_t>(dividend) / static_cast<uint32_t>(divisor));
    }
    // 未テスト
    // 計算量: O(1)
    static int remainderUnsigned(int dividend, int divisor) {
        return static_cast<int>(static_cast<uint32_t>(dividend) % static_cast<uint32_t>(divisor));
    }
    // 未テスト
    // 計算量: O(1)
    static int compareUnsigned(int x, int y) {
        uint32_t ux = static_cast<uint32_t>(x);
        uint32_t uy = static_cast<uint32_t>(y);
        return (ux > uy) - (ux < uy);
    }
    // 未テスト
    // 計算量: O(1)
    static long long toUnsignedLong(int x) {
        return static_cast<long long>(static_cast<uint32_t>(x));
    }
    static int reverse(int x) {
        uint32_t u = static_cast<uint32_t>(x);
        u = ((u & 0x55555555U) << 1) | ((u & 0xAAAAAAAAU) >> 1);
        u = ((u & 0x33333333U) << 2) | ((u & 0xCCCCCCCCU) >> 2);
        u = ((u & 0x0F0F0F0FU) << 4) | ((u & 0xF0F0F0F0U) >> 4);
        u = ((u & 0x00FF00FFU) << 8) | ((u & 0xFF00FF00U) >> 8);
        u = (u << 16) | (u >> 16);
        return static_cast<int>(u);
    }
    static int reverseBytes(int x) {
        return static_cast<int>(__builtin_bswap32(static_cast<uint32_t>(x)));
    }
    static JString toBinaryString(int x) {
        if (x == 0) return "0";
        uint32_t u = static_cast<uint32_t>(x);
        string s;
        while (u > 0) {
            s.push_back((u & 1) ? '1' : '0');
            u >>= 1;
        }
        std::reverse(s.begin(), s.end());
        return s;
    }
    static JString toHexString(int x) {
        if (x == 0) return "0";
        uint32_t u = static_cast<uint32_t>(x);
        stringstream ss;
        ss << std::hex << u;
        return ss.str();
    }
    static JString toOctalString(int x) {
        if (x == 0) return "0";
        uint32_t u = static_cast<uint32_t>(x);
        stringstream ss;
        ss << std::oct << u;
        return ss.str();
    }
    // 未テスト
    // 計算量: O(log_radix |x|)
    static JString toUnsignedString(int x, int radix = 10) {
        uint32_t u = static_cast<uint32_t>(x);
        if (u == 0) return "0";
        string s;
        while (u > 0) {
            int rem = u % radix;
            s.push_back(rem < 10 ? '0' + rem : 'a' + (rem - 10));
            u /= radix;
        }
        std::reverse(s.begin(), s.end());
        return s;
    }
    static JString toString(int x, int radix = 10) {
        if (radix == 10) return std::to_string(x);
        if (radix == 2) return toBinaryString(x);
        if (radix == 16) return toHexString(x);
        if (radix == 8) return toOctalString(x);
        return std::to_string(x);
    }
    static int parseInt(const JString& x, int radix = 10) { return stoi(x, nullptr, radix); }
    // 未テスト
    // 計算量: O(|x|)
    static int parseUnsignedInt(const JString& x, int radix = 10) { return static_cast<int>(stoul(x, nullptr, radix)); }
    static int valueOf(const JString& x, int radix = 10) { return stoi(x, nullptr, radix); }
    static int valueOf(int x) { return x; }
};
template<class T> struct Comparable {
    virtual ~Comparable() = default;
    virtual int compareTo(T) = 0;
};
struct Runnable {
    virtual ~Runnable() = default;
    virtual void run() = 0;
};
struct AutoCloseable {
    virtual ~AutoCloseable() = default;
    virtual void close() = 0;
};
using Closeable = AutoCloseable;
struct Serializable {};
struct Cloneable {};
struct JRandom {
    mutable mt19937_64 engine;
    JRandom() : engine(chrono::steady_clock::now().time_since_epoch().count()) {}
    explicit JRandom(long long seed) : engine(seed) {}
    // 未テスト
    // 計算量: O(1)
    unsigned long long operator()() const { return engine(); }
    // 未テスト
    // 計算量: O(1)
    void setSeed(long long seed) const { engine.seed(seed); }
    int nextInt() const { return static_cast<int>(engine()); }
    int nextInt(int bound) const { return uniform_int_distribution<int>(0, bound - 1)(engine); }
    int nextInt(int origin, int bound) const { return uniform_int_distribution<int>(origin, bound - 1)(engine); }
    long long nextLong() const { return static_cast<long long>(engine()); }
    long long nextLong(long long bound) const { return uniform_int_distribution<long long>(0, bound - 1)(engine); }
    long long nextLong(long long origin, long long bound) const { return uniform_int_distribution<long long>(origin, bound - 1)(engine); }
    double nextDouble() const { return uniform_real_distribution<double>(0.0, 1.0)(engine); }
    double nextDouble(double bound) const { return uniform_real_distribution<double>(0.0, bound)(engine); }
    double nextDouble(double origin, double bound) const { return uniform_real_distribution<double>(origin, bound)(engine); }
    float nextFloat() const { return uniform_real_distribution<float>(0.0f, 1.0f)(engine); }
    bool nextBoolean() const { return (engine() & 1) != 0; }
    // 未テスト
    // 計算量: O(1)
    JRandom split() const { return JRandom(static_cast<long long>(engine())); }
    double nextGaussian() const { return normal_distribution<double>(0.0, 1.0)(engine); }
};
struct ArrayUtils2D;
struct ArrayUtils;
struct FastScanner;
struct Hash;
struct MinimumCostFlow;
struct MyPrintWriter;
template <class Key>
struct OpenHashSet;
struct DiscreteLogarithm;
template <class Monoid>
struct MonoidStrategy;
template <class T>
struct SegTree;
struct Permutation;
struct Main;

struct ArrayUtils2D : public std::enable_shared_from_this<ArrayUtils2D> {
    virtual ~ArrayUtils2D() = default;
    ArrayUtils2D();
    static void fill(const vector<vector<char>>& a_const, char v);
};

struct ArrayUtils : public std::enable_shared_from_this<ArrayUtils> {
    virtual ~ArrayUtils() = default;
    ArrayUtils();
    static int argMax(const vector<long long>& a_const);
    static void decrementAll(const vector<int>& a_const);
    static void fill(const vector<vector<char>>& a_const, char v);
    static long long max(const vector<long long>& a_const);
};

struct FastScanner : public std::enable_shared_from_this<FastScanner> {
    virtual ~FastScanner() = default;
    FastScanner();
    static shared_ptr<struct FastScanner> getInstance();
    virtual bool hasNext();
    virtual bool hasNextByte();
    virtual bool isPrintableChar(int c);
    virtual int nextInt();
    virtual vector<int> nextInts(int n);
    virtual long long nextLong();
    virtual int readByte();
    inline static shared_ptr<struct FastScanner> instance = (shared_ptr<struct FastScanner>){};
    JInputStream in = JInputStream();
    vector<int8_t> buffer = vector<int8_t>((int)((unsigned int)(1) << 16));
    int ptr = 0;
    int buflen = 0;
};

struct Hash : public std::enable_shared_from_this<Hash> {
    template <class KInner>
struct Strategy;
template <class KInner>
struct Strategy {
        virtual ~Strategy() = default;
        virtual bool equals(const KInner& a_const, const KInner& b_const) = 0;
        virtual int hashCode(const KInner& o_const) = 0;
    };

    virtual ~Hash() = default;
    Hash();
    template <class K>
    static shared_ptr<struct Strategy<K>> defaultStrategy();
};

struct MinimumCostFlow : public std::enable_shared_from_this<MinimumCostFlow> {
    struct Edge;
struct Edge : public std::enable_shared_from_this<Edge> {
        MinimumCostFlow* outer;
        virtual ~Edge() = default;
        Edge(MinimumCostFlow* outer_, int from, int to, long long cost, long long cap) : outer(outer_)         {
            (this->from = from);
            (this->to = to);
            (this->cost_ = cost);
            (this->cap = cap);
        }
        virtual void addFlow(long long add) {
            (this->flow += add);
            (this->reverseEdge->flow -= add);
            if ((this->flow > this->cap)) {
                throw runtime_error("AssertionError");
            }
            if ((this->reverseEdge->flow > this->reverseEdge->cap)) {
                throw runtime_error("AssertionError");
            }
            (outer->excess[this->from] -= add);
            (outer->excess[this->to] += add);
        }
        virtual long long reducedCost() {
            return (this->cost_ - (outer->potential[this->to] - outer->potential[this->from]));
        }
        virtual long long res() {
            return (this->cap - this->flow);
        }
        virtual JString toString() {
            return jconcat(jconcat(jconcat(jconcat(jconcat(jconcat(jconcat(jconcat(jconcat(JString("from "), this->from), JString(" to ")), this->to), JString(" : flow=")), this->flow), JString(", cap=")), this->cap), JString(", cost=")), this->cost_);
        }
        int from = {};
        int to = {};
        long long cost_ = {};
        long long cap = {};
        long long flow = 0;
        shared_ptr<struct Edge> reverseEdge = {};
    };

    virtual ~MinimumCostFlow() = default;
    MinimumCostFlow(int N);
    virtual void addEdge(int from, int to, long long cost, long long cap);
    virtual void addExcess(int v, long long supply);
    virtual void addFixedFlowEdge(int from, int to, long long cost, long long flow);
    virtual JOptionalVal<long long> minCostCirculation();
    virtual long long minCostFlowAtMost(int s, int t, long long cap);
    virtual void updateDistance(int src);
    int N = {};
    vector<JList<shared_ptr<struct Edge>>> g = {};
    vector<JList<shared_ptr<struct Edge>>> ig = {};
    vector<long long> excess = {};
    vector<long long> potential = {};
    long long INF = (JLong::MAX_VALUE / 3);
    vector<shared_ptr<struct Edge>> incommingShortestPathEdge = {};
    vector<long long> d = {};
    long long base = 0;
};

struct MyPrintWriter : public std::enable_shared_from_this<MyPrintWriter>, public JPrintWriter {
    using JPrintWriter::println;
    virtual ~MyPrintWriter() = default;
    MyPrintWriter();
    MyPrintWriter(const JPrintWriter& out_const);
    static shared_ptr<struct MyPrintWriter> getInstance();
    virtual void println(const vector<vector<char>>& a_const);
    inline static shared_ptr<struct MyPrintWriter> instance = (shared_ptr<struct MyPrintWriter>){};
};

template <class Key>
struct OpenHashSet : public std::enable_shared_from_this<OpenHashSet<Key>> {
    virtual ~OpenHashSet() = default;
    OpenHashSet() : OpenHashSet<Key>(Hash::defaultStrategy<Key>())     {
    }
    OpenHashSet(const shared_ptr<typename Hash::template Strategy<Key>>& strategy_const)     {
        shared_ptr<typename Hash::template Strategy<Key>> strategy = strategy_const;
        (this->keys = vector<Key>(OpenHashSet<int>::defaultCapacity));
        (this->deleted = vector<bool>(OpenHashSet<int>::defaultCapacity));
        (this->strategy = strategy);
    }
    OpenHashSet(const shared_ptr<typename Hash::template Strategy<Key>>& strategy_const, int initialCapacity)     {
        shared_ptr<typename Hash::template Strategy<Key>> strategy = strategy_const;
        int capacity = (JInteger::highestOneBit(initialCapacity) * 2);
        (this->mask = (capacity - 1));
        (this->keys = vector<Key>(capacity));
        (this->deleted = vector<bool>(capacity));
        (this->strategy = strategy);
    }
    virtual void add(const typename Nullable<Key>::type& key_const) {
        auto& key = const_cast<typename Nullable<Key>::type&>(key_const);
        if (jisNull(key)) {
            throw runtime_error("AssertionError");
        }
        if (((this->size_ + 1) > (static_cast<int>(this->keys.size()) * OpenHashSet<int>::defaultLoadFactor))) {
            this->resize((static_cast<int>(this->keys.size()) * 2));
        }
        int start = this->hash(key);
        int i = start;
        int firstDeleted = (-1);
        do {
            if (jisNull(this->keys[i])) {
                if ((!this->deleted[i])) {
                    int target = ((firstDeleted != (-1)) ? firstDeleted : i);
                    (this->keys[target] = key);
                    (this->deleted[target] = false);
                    (++this->size_);
                    return;
                } else {
                    if ((firstDeleted == (-1))) {
                        (firstDeleted = i);
                    }
                }
            } else {
                if (this->strategy->equals(this->keys[i], key)) {
                    return;
                }
            }
            (i = ((i + 1) & this->mask));
        } while ((i != start));
        if ((firstDeleted != (-1))) {
            (this->keys[firstDeleted] = key);
            (this->deleted[firstDeleted] = false);
            (++this->size_);
            return;
        }
        throw runtime_error("AssertionError");
    }
    virtual bool contains(const typename Nullable<Key>::type& key_const) {
        auto& key = const_cast<typename Nullable<Key>::type&>(key_const);
        if (jisNull(key)) {
            return false;
        }
        int start = this->hash(key);
        int i = start;
        do {
            if ((jisNull(this->keys[i]) && (!this->deleted[i]))) {
                return false;
            }
            if ((!jisNull(this->keys[i]) && this->strategy->equals(this->keys[i], key))) {
                return true;
            }
            (i = ((i + 1) & this->mask));
        } while ((i != start));
        return false;
    }
    virtual bool equals(const JObject& o_const) {
        auto& o = const_cast<JObject&>(o_const);
        if (false) {
            return true;
        }
        if ((!jisInstance<shared_ptr<struct OpenHashSet<Key>>>(o))) {
            return false;
        }
        shared_ptr<struct OpenHashSet<Key>> other = any_cast<shared_ptr<struct OpenHashSet<Key>>>(o);
        if ((this->size() != other->size())) {
            return false;
        }
        for (int i = 0; (i < static_cast<int>(this->keys.size())); (i++)) {
            if ((!jisNull(this->keys[i]) && (!this->deleted[i]))) {
                bool contains = dynamic_pointer_cast<struct OpenHashSet<JObject>>(other)->contains(this->keys[i]);
                if ((!contains)) {
                    return false;
                }
            }
        }
        return true;
    }
    virtual int hash(const Key& key_const) {
        auto& key = const_cast<Key&>(key_const);
        return (this->strategy->hashCode(key) & this->mask);
    }
    virtual int hashCode() {
        int h = 0;
        for (int i = 0; (i < static_cast<int>(this->keys.size())); (i++)) {
            if ((!jisNull(this->keys[i]) && (!this->deleted[i]))) {
                (h += this->strategy->hashCode(this->keys[i]));
            }
        }
        return h;
    }
    virtual JIterator<Key> iterator() const {
        return [=, this]() {
    auto outer_ptr = const_cast<std::decay_t<decltype(*this)>*>(this);
    auto __init_0 = 0;
    struct __Anon : public std::enable_shared_from_this<__Anon> {
        decltype(outer_ptr) outer;
        int id_;
        __Anon(decltype(outer_ptr) o, const int& __p_0) : outer(o), id_(__p_0) {}
        bool hasNext() {
            while ((this->id_ < static_cast<int>(outer->keys.size()))) {
                if ((!jisNull(outer->keys[this->id_]) && (!outer->deleted[this->id_]))) {
                    return true;
                }
                (++this->id_);
            }
            return false;
        }
        Key next() {
            if ((!this->hasNext())) {
                throw runtime_error("NoSuchElementException");
            }
            return outer->keys[(this->id_++)];
        }
    };
    return JIterator<Key>(make_shared<__Anon>(outer_ptr, __init_0));
}();
    }
    virtual void resize(int newCapacity) {
        auto oldKeys = this->keys;
        (this->keys = vector<Key>(newCapacity));
        (this->deleted = vector<bool>(newCapacity));
        (this->mask = (newCapacity - 1));
        (this->size_ = 0);
        for (int i = 0; (i < static_cast<int>(oldKeys.size())); (i++)) {
            if (!jisNull(oldKeys[i])) {
                this->add(oldKeys[i]);
            }
        }
    }
    virtual int size() {
        return this->size_;
    }
    inline static int defaultCapacity = 16;
    int size_ = 0;
    vector<Key> keys = {};
    vector<bool> deleted = {};
    int mask = (OpenHashSet<int>::defaultCapacity - 1);
    inline static double defaultLoadFactor = 0.75;
    shared_ptr<typename Hash::template Strategy<Key>> strategy = {};
    struct CppIterator {
        JIterator<Key> it;
        using ValueType = std::decay_t<decltype(it.next())>;
        ValueType current_val{};
        bool active = false;
        CppIterator() = default;
        explicit CppIterator(const JIterator<Key>& iter) : it(iter) {
            if (it.hasNext()) { current_val = it.next(); active = true; }
        }
        bool operator!=(const CppIterator&) const { return active; }
        void operator++() {
            if (it.hasNext()) { current_val = it.next(); }
            else { active = false; }
        }
        ValueType operator*() const { return current_val; }
    };
    CppIterator begin() { return CppIterator(this->iterator()); }
    CppIterator end() { return CppIterator(); }
    CppIterator begin() const { return CppIterator(const_cast<std::decay_t<decltype(*this)>*>(this)->iterator()); }
    CppIterator end() const { return CppIterator(); }
};

struct DiscreteLogarithm : public std::enable_shared_from_this<DiscreteLogarithm> {
    virtual ~DiscreteLogarithm() = default;
    DiscreteLogarithm();
    template <class S, class F>
    static long long discreteLog(const F& baby_const, const F& giant_const, const S& s_const, const S& t_const, const function<S(F, S)>& mapping_const, long long maxSearch, int giantStride, const shared_ptr<typename Hash::template Strategy<S>>& strategy_const);
    template <class S, class F>
    static long long discreteLog(const F& f_const, const S& s_const, const S& t_const, const function<S(F, S)>& mapping_const, const function<F(F, F)>& composition_const, long long maxSearch);
    template <class S, class F>
    static long long discreteLog(const F& f_const, const S& s_const, const S& t_const, const function<S(F, S)>& mapping_const, const function<F(F, F)>& composition_const, long long maxSearch, const shared_ptr<typename Hash::template Strategy<S>>& strategy_const);
};

template <class Monoid>
struct MonoidStrategy {
    virtual ~MonoidStrategy() = default;
    virtual long long discreteLog(const Monoid& a_const, const Monoid& t_const, long long maxSearch) {
        auto& a = const_cast<Monoid&>(a_const);
        auto& t = const_cast<Monoid&>(t_const);
        return DiscreteLogarithm::discreteLog<Monoid, Monoid>(a, this->identity(), t, [this](auto&&... args) { return this->mul(std::forward<decltype(args)>(args)...); }, [this](auto&&... args) { return this->mul(std::forward<decltype(args)>(args)...); }, maxSearch);
    }
    virtual Monoid identity() = 0;
    virtual Monoid mul(const Monoid& a_const, const Monoid& b_const) = 0;
    virtual Monoid pow(const Monoid& a_const, long long n) {
        Monoid a = a_const;
        if ((n < 0)) {
            throw runtime_error("AssertionError");
        }
        Monoid ret = this->identity();
        while ((n != 0)) {
            if (((n % 2) == 1)) {
                (ret = this->mul(ret, a));
            }
            (a = this->mul(a, a));
            (n /= 2);
        }
        return ret;
    }
};

template <class T>
struct SegTree : public std::enable_shared_from_this<SegTree<T>> {
    virtual ~SegTree() = default;
    SegTree(int n, const shared_ptr<struct MonoidStrategy<T>>& strategy_const) : SegTree<T>(n, [obj=strategy_const](auto&&... args) mutable { return obj->mul(std::forward<decltype(args)>(args)...); }, strategy_const->identity())     {
        shared_ptr<struct MonoidStrategy<T>> strategy = strategy_const;
    }
    SegTree(int n_, const function<T(T, T)>& op_const)     {
        function<T(T, T)> op = op_const;
        (this->inputN = n_);
        (this->n = (int)((unsigned int)(JInteger::highestOneBit(n_)) << 1));
        (this->v = vector<T>((2 * this->n)));
        for (int i = 0; (i < static_cast<int>(this->v.size())); (++i)) {
            (this->v[i] = this->identity_);
        }
        (this->op_ = op);
    }
    template<class F0, class F1, class = enable_if_t<!is_same_v<decay_t<F0>, SegTree> && !(is_same_v<decay_t<F1>, function<T(T, T)>>)>> SegTree(F0&& p0, F1&& p1) : SegTree(std::forward<F0>(p0), function<T(T, T)>(std::forward<F1>(p1))) {}

    SegTree(int n, const function<T(T, T)>& op_const, const T& identiy_const)     {
        function<T(T, T)> op = op_const;
        auto& identiy = const_cast<T&>(identiy_const);
        (this->n = (int)((unsigned int)(JInteger::highestOneBit(n)) << 1));
        (this->inputN = n);
        (this->v = vector<T>((2 * this->n)));
        (this->identity_ = identiy);
        for (int i = 0; (i < static_cast<int>(this->v.size())); (++i)) {
            (this->v[i] = this->identity_);
        }
        (this->op_ = op);
    }
    SegTree(const vector<T>& a_const, const shared_ptr<struct MonoidStrategy<T>>& strategy_const) : SegTree<T>(static_cast<int>(a_const.size()), strategy_const)     {
        auto& a = const_cast<vector<T>&>(a_const);
        shared_ptr<struct MonoidStrategy<T>> strategy = strategy_const;
        this->build(a);
    }
    SegTree(const vector<T>& a_const, const function<T(T, T)>& op_const, const T& identity_const) : SegTree<T>(static_cast<int>(a_const.size()), op_const, identity_const)     {
        auto& a = const_cast<vector<T>&>(a_const);
        auto& op = const_cast<function<T(T, T)>&>(op_const);
        auto& identity = const_cast<T&>(identity_const);
        this->build(a);
    }
    virtual void build(const vector<T>& a_const) {
        auto& a = const_cast<vector<T>&>(a_const);
        for (int i = 0; (i < static_cast<int>(a.size())); (i++)) {
            (this->v[this->id(i, (i + 1))] = a[i]);
        }
        for (int i = (this->n - 1); (i >= 1); (i--)) {
            (this->v[i] = this->op(this->v[(2 * i)], this->v[((2 * i) + 1)]));
        }
    }
    virtual T fold(int l, int r) {
        (r = jmin(r, this->n));
        (l = jmax(l, 0));
        if (((r - l) <= 0)) {
            return this->identity_;
        }
        int ml = (l + JInteger::lowestOneBit(l));
        int mr = (r - JInteger::lowestOneBit(r));
        if (((l < ml) && (ml <= r))) {
            return this->op(this->v[this->id(l, ml)], this->fold(ml, r));
        } else {
            return this->op(this->fold(l, mr), this->v[this->id(mr, r)]);
        }
    }
    virtual int id(int a, int b) {
        int w = (b - a);
        return ((this->n / w) + (a / w));
    }
    virtual T op(const T& a_const, const T& b_const) {
        auto& a = const_cast<T&>(a_const);
        auto& b = const_cast<T&>(b_const);
        if ((a == this->identity_)) {
            return b;
        }
        if ((b == this->identity_)) {
            return a;
        }
        return this->op_(a, b);
    }
    virtual void set(int k, const T& t_const) {
        auto& t = const_cast<T&>(t_const);
        (k = this->id(k, (k + 1)));
        (this->v[k] = t);
        while ((k != this->id(0, this->n))) {
            (k /= 2);
            (this->v[k] = this->op(this->v[(2 * k)], this->v[((2 * k) + 1)]));
        }
    }
    virtual JString toString() {
        JString ret = JString("");
        for (int w = 1; (w <= this->n); (w *= 2)) {
            for (int i = 0; (i < w); (++i)) {
                (ret += jconcat((jisNull(this->v[(i + w)]) ? JString("id") : jstr(this->v[(i + w)])), jrepeat(JString(" "), ((this->n == w) ? 1 : (((2 * this->n) / w) - 1)))));
            }
            (ret += JString("\n"));
        }
        return ret;
    }
    int n = {};
    int inputN = {};
    vector<T> v = {};
    T identity_ = {};
    function<T(T, T)> op_ = {};
};

struct Permutation : public std::enable_shared_from_this<Permutation> {
    virtual ~Permutation() = default;
    Permutation();
    static long long inversion(const vector<int>& a_const);
};

struct Main : public std::enable_shared_from_this<Main> {
    virtual ~Main() = default;
    Main();
    virtual int cost(int i0, int v0, int i1, int v1);
    virtual long long eval(const vector<int>& A_const, const vector<vector<char>>& S_const);
    static void javaMain(const vector<JString>& args_const);
    virtual void run();
    inline static JRandom rnd = JRandom();
};

ArrayUtils2D::ArrayUtils2D() {
}

ArrayUtils::ArrayUtils() {
}

FastScanner::FastScanner() {
}

Hash::Hash() {
}

MinimumCostFlow::MinimumCostFlow(int N) {
    (this->N = N);
    (this->g = vector<JList<shared_ptr<struct Edge>>>(this->N));
    (this->ig = vector<JList<shared_ptr<struct Edge>>>(this->N));
    (this->excess = vector<long long>(this->N));
    (this->potential = vector<long long>(this->N));
    (this->d = vector<long long>(this->N));
    (this->incommingShortestPathEdge = vector<shared_ptr<struct Edge>>(this->N));
    for (int i = 0; (i < this->N); (++i)) {
        (this->g[i] = JList<shared_ptr<struct Edge>>());
        (this->ig[i] = JList<shared_ptr<struct Edge>>());
    }
}

MyPrintWriter::MyPrintWriter() : JPrintWriter(JPrintWriter()) {
}

MyPrintWriter::MyPrintWriter(const JPrintWriter& out_const) : JPrintWriter(out_const) {
    auto& out = const_cast<JPrintWriter&>(out_const);
}

DiscreteLogarithm::DiscreteLogarithm() {
}

Permutation::Permutation() {
}

Main::Main() {
}

void ArrayUtils2D::fill(const vector<vector<char>>& a_const, char v) {
    auto& a = const_cast<vector<vector<char>>&>(a_const);
    for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
        for (int j = 0; (j < static_cast<int>(a[i].size())); (++j)) {
            (a[i][j] = v);
        }
    }
}

int ArrayUtils::argMax(const vector<long long>& a_const) {
    auto& a = const_cast<vector<long long>&>(a_const);
    int ret = 0;
    for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
        if ((a[i] > a[ret])) {
            (ret = i);
        }
    }
    return ret;
}

void ArrayUtils::decrementAll(const vector<int>& a_const) {
    auto& a = const_cast<vector<int>&>(a_const);
    for (int i = 0; (i < static_cast<int>(a.size())); (i++)) {
        (a[i]--);
    }
}

void ArrayUtils::fill(const vector<vector<char>>& a_const, char v) {
    auto& a = const_cast<vector<vector<char>>&>(a_const);
    ArrayUtils2D::fill(a, v);
}

long long ArrayUtils::max(const vector<long long>& a_const) {
    auto& a = const_cast<vector<long long>&>(a_const);
    long long ret = JLong::MIN_VALUE;
    for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
        (ret = jmax(ret, a[i]));
    }
    return ret;
}

shared_ptr<struct FastScanner> FastScanner::getInstance() {
    if ((jisNull(FastScanner::instance))) {
        (FastScanner::instance = make_shared<struct FastScanner>());
    }
    return FastScanner::instance;
}

bool FastScanner::hasNext() {
    while ((this->hasNextByte() && (!this->isPrintableChar(this->buffer[this->ptr])))) {
        (this->ptr++);
    }
    return this->hasNextByte();
}

bool FastScanner::hasNextByte() {
    if ((this->ptr < this->buflen)) {
        return true;
    }
    (this->ptr = 0);
    try {
        (this->buflen = this->in.read(this->buffer));
    } catch (const exception& e) {
        (void)0;
    }
    return (this->buflen > 0);
}

bool FastScanner::isPrintableChar(int c) {
    return ((33 <= c) && (c <= 126));
}

int FastScanner::nextInt() {
    return static_cast<int>(this->nextLong());
}

vector<int> FastScanner::nextInts(int n) {
    vector<int> a = vector<int>(n);
    for (int i = 0; (i < n); (++i)) {
        (a[i] = this->nextInt());
    }
    return a;
}

long long FastScanner::nextLong() {
    if ((!this->hasNext())) {
        throw runtime_error("NoSuchElementException");
    }
    long long n = 0;
    bool minus = false;
    int b = this->readByte();
    if ((b == '-')) {
        (minus = true);
        (b = this->readByte());
    }
    while (((b >= '0') && (b <= '9'))) {
        (n = (((n << 1) + (n << 3)) + (b - '0')));
        (b = this->readByte());
    }
    return (minus ? (-n) : n);
}

int FastScanner::readByte() {
    if (this->hasNextByte()) {
        return this->buffer[(this->ptr++)];
    } else {
        return (-1);
    }
}

template <class K>
shared_ptr<typename Hash::template Strategy<K>> Hash::defaultStrategy() {
    long long x{};
    return [=]() {
    auto outer_ptr = nullptr;
    struct __Anon : public Strategy<K>, public std::enable_shared_from_this<__Anon> {
        decltype(outer_ptr) outer;
        __Anon(decltype(outer_ptr) o) : outer(o) {}
        bool equals(const K& a_const, const K& b_const) override {
        auto& a = const_cast<K&>(a_const);
        auto& b = const_cast<K&>(b_const);
        if ((jisInstance<vector<int>>(a) && jisInstance<vector<int>>(b))) {
            return (jcast<vector<int>>(a) == jcast<vector<int>>(b));
        }
        if ((jisInstance<vector<long long>>(a) && jisInstance<vector<long long>>(b))) {
            return (jcast<vector<long long>>(a) == jcast<vector<long long>>(b));
        }
        if ((jisInstance<vector<char>>(a) && jisInstance<vector<char>>(b))) {
            return (jcast<vector<char>>(a) == jcast<vector<char>>(b));
        }
        if ((jisInstance<vector<bool>>(a) && jisInstance<vector<bool>>(b))) {
            return (jcast<vector<bool>>(a) == jcast<vector<bool>>(b));
        }
        if ((jisInstance<vector<int8_t>>(a) && jisInstance<vector<int8_t>>(b))) {
            return (jcast<vector<int8_t>>(a) == jcast<vector<int8_t>>(b));
        }
        if ((jisInstance<vector<int16_t>>(a) && jisInstance<vector<int16_t>>(b))) {
            return (jcast<vector<int16_t>>(a) == jcast<vector<int16_t>>(b));
        }
        if ((jisInstance<vector<float>>(a) && jisInstance<vector<float>>(b))) {
            return (jcast<vector<float>>(a) == jcast<vector<float>>(b));
        }
        if ((jisInstance<vector<double>>(a) && jisInstance<vector<double>>(b))) {
            return (jcast<vector<double>>(a) == jcast<vector<double>>(b));
        }
        if ((jisInstance<vector<JObject>>(a) && jisInstance<vector<JObject>>(b))) {
            return (jcast<vector<JObject>>(a) == jcast<vector<JObject>>(b));
        }
        return jequals(a, b);
    }
        int hashCode(const K& o_const) override {
        auto& o = const_cast<K&>(o_const);
        long long x{};
        if (jisInstance<vector<int>>(o)) {
            return static_cast<int>(jhash(jcast<vector<int>>(o)));
        }
        if (jisInstance<vector<long long>>(o)) {
            return static_cast<int>(jhash(jcast<vector<long long>>(o)));
        }
        if (jisInstance<vector<char>>(o)) {
            return static_cast<int>(jhash(jcast<vector<char>>(o)));
        }
        if (jisInstance<vector<bool>>(o)) {
            return static_cast<int>(jhash(jcast<vector<bool>>(o)));
        }
        if (jisInstance<vector<int8_t>>(o)) {
            return static_cast<int>(jhash(jcast<vector<int8_t>>(o)));
        }
        if (jisInstance<vector<int16_t>>(o)) {
            return static_cast<int>(jhash(jcast<vector<int16_t>>(o)));
        }
        if (jisInstance<vector<float>>(o)) {
            return static_cast<int>(jhash(jcast<vector<float>>(o)));
        }
        if (jisInstance<vector<double>>(o)) {
            return static_cast<int>(jhash(jcast<vector<double>>(o)));
        }
        if (jisInstance<vector<JObject>>(o)) {
            return static_cast<int>(jhash(jcast<vector<JObject>>(o)));
        }
        if (jisInstance(o, x)) {
            (x ^= jusr(x, 33));
            (x *= -49064778989728563LL);
            (x ^= jusr(x, 33));
            (x *= -4265267296055464877LL);
            (x ^= jusr(x, 33));
            return x;
        }
        return static_cast<int>(jhash(o));
    }
    };
    return static_pointer_cast<Strategy<K>>(make_shared<__Anon>(outer_ptr));
}();
}

void MinimumCostFlow::addEdge(int from, int to, long long cost, long long cap) {
    shared_ptr<struct Edge> e = make_shared<struct Edge>(this, from, to, cost, cap);
    shared_ptr<struct Edge> ie = make_shared<struct Edge>(this, to, from, (-cost), 0);
    (e->reverseEdge = ie);
    (ie->reverseEdge = e);
    this->g[from].add(e);
    this->ig[to].add(ie);
}

void MinimumCostFlow::addExcess(int v, long long supply) {
    (this->excess[v] += supply);
}

void MinimumCostFlow::addFixedFlowEdge(int from, int to, long long cost, long long flow) {
    this->addExcess(from, (-flow));
    this->addExcess(to, flow);
    (this->base += (flow * cost));
}

JOptionalVal<long long> MinimumCostFlow::minCostCirculation() {
    for (auto edges : this->g) {
        for (auto edge : edges) {
            if ((edge->reducedCost() < 0)) {
                edge->addFlow(edge->cap);
            }
        }
    }
    while ((ArrayUtils::max(this->excess) > 0)) {
        int src = ArrayUtils::argMax(this->excess);
        this->updateDistance(src);
        int dst = 0;
        while (((dst < this->N) && ((this->d[dst] == this->INF) || (this->excess[dst] >= 0)))) {
            (++dst);
        }
        if ((dst == this->N)) {
            return nullptr;
        }
        long long addFlow = jmin(this->excess[src], (-this->excess[dst]));
        {
            int cur = dst;
            while ((cur != src)) {
                (addFlow = jmin(addFlow, this->incommingShortestPathEdge[cur]->res()));
                (cur = this->incommingShortestPathEdge[cur]->from);
            }
        }
        {
            int cur = dst;
            while ((cur != src)) {
                this->incommingShortestPathEdge[cur]->addFlow(addFlow);
                (cur = this->incommingShortestPathEdge[cur]->from);
            }
        }
    }
    long long ret = 0;
    for (auto edges : this->g) {
        for (auto edge : edges) {
            (ret += (edge->flow * edge->cost_));
        }
    }
    return (ret + this->base);
}

long long MinimumCostFlow::minCostFlowAtMost(int s, int t, long long cap) {
    this->addEdge(t, s, 0, cap);
    return this->minCostCirculation();
}

void MinimumCostFlow::updateDistance(int src) {
    jfill(this->d, this->INF);
    jfill(this->incommingShortestPathEdge, nullptr);
    (this->d[src] = 0);
struct State {
        virtual ~State() = default;
        State(int v, long long d)         {
            (this->v_ = v);
            (this->d_ = d);
        }
        virtual int compareTo(const shared_ptr<struct State>& o_const) {
            shared_ptr<struct State> o = o_const;
            return JLong::compare(this->d_, o->d_);
        }
        virtual long long d() {
            return this->d_;
        }
        virtual int v() {
            return this->v_;
        }
        int v_ = {};
        long long d_ = {};
    };

    JPriorityQueue<shared_ptr<struct State>> pq = JPriorityQueue<shared_ptr<struct State>>();
    pq.add(make_shared<struct State>(src, 0));
    while ((!pq.empty())) {
        shared_ptr<struct State> state = pq.poll();
        if ((state->d_ > this->d[state->v_])) {
            continue;
        }
        for (shared_ptr<struct Edge> e : this->g[state->v_]) {
            if ((e->res() == 0)) {
                continue;
            }
            if ((this->d[e->to] > (state->d_ + e->reducedCost()))) {
                (this->d[e->to] = (state->d_ + e->reducedCost()));
                pq.add(make_shared<struct State>(e->to, this->d[e->to]));
                (this->incommingShortestPathEdge[e->to] = e);
            }
        }
        for (shared_ptr<struct Edge> e : this->ig[state->v_]) {
            if ((e->res() == 0)) {
                continue;
            }
            if ((this->d[e->to] > (state->d_ + e->reducedCost()))) {
                (this->d[e->to] = (state->d_ + e->reducedCost()));
                pq.add(make_shared<struct State>(e->to, this->d[e->to]));
                (this->incommingShortestPathEdge[e->to] = e);
            }
        }
    }
    for (int i = 0; (i < this->N); (++i)) {
        if ((this->d[i] != this->INF)) {
            (this->potential[i] += this->d[i]);
        }
    }
}

shared_ptr<struct MyPrintWriter> MyPrintWriter::getInstance() {
    if ((jisNull(MyPrintWriter::instance))) {
        (MyPrintWriter::instance = make_shared<struct MyPrintWriter>());
    }
    return MyPrintWriter::instance;
}

void MyPrintWriter::println(const vector<vector<char>>& a_const) {
    auto& a = const_cast<vector<vector<char>>&>(a_const);
    for (int i = 0; (i < static_cast<int>(a.size())); (i++)) {
        this->println(a[i]);
    }
}

template <class S, class F>
long long DiscreteLogarithm::discreteLog(const F& baby_const, const F& giant_const, const S& s_const, const S& t_const, const function<S(F, S)>& mapping_const, long long maxSearch, int giantStride, const shared_ptr<typename Hash::template Strategy<S>>& strategy_const) {
    auto& baby = const_cast<F&>(baby_const);
    auto& giant = const_cast<F&>(giant_const);
    auto& s = const_cast<S&>(s_const);
    auto& t = const_cast<S&>(t_const);
    auto& mapping = const_cast<function<S(F, S)>&>(mapping_const);
    shared_ptr<typename Hash::template Strategy<S>> strategy = strategy_const;
    if ((jisNull(strategy))) {
        if ((s == t)) {
            return 0;
        }
    } else {
        if (strategy->equals(s, t)) {
            return 0;
        }
    }
    if ((maxSearch <= 0)) {
        return (-1);
    }
    shared_ptr<struct OpenHashSet<S>> ys = ((jisNull(strategy)) ? make_shared<struct OpenHashSet<S>>() : make_shared<struct OpenHashSet<S>>(strategy));
    {
        S yt = t;
        for (int i = 0; (i < giantStride); (++i)) {
            ys->add(yt);
            (yt = mapping(baby, yt));
        }
    }
    int numFails = 0;
    S cur = s;
    for (long long k = 1; ; (++k)) {
        S nxt = mapping(giant, cur);
        if (ys->contains(nxt)) {
            for (int i = 1; (i <= giantStride); (++i)) {
                (cur = mapping(baby, cur));
                bool match = ((jisNull(strategy)) ? (cur == t) : strategy->equals(cur, t));
                if (match) {
                    long long ret = (((k - 1) * giantStride) + i);
                    return ((ret <= maxSearch) ? ret : (-1));
                }
            }
            (++numFails);
        } else {
            (cur = nxt);
        }
        if (((numFails >= 2) || ((k * giantStride) > maxSearch))) {
            return (-1);
        }
    }
}

template <class S, class F>
long long DiscreteLogarithm::discreteLog(const F& f_const, const S& s_const, const S& t_const, const function<S(F, S)>& mapping_const, const function<F(F, F)>& composition_const, long long maxSearch) {
    auto& f = const_cast<F&>(f_const);
    auto& s = const_cast<S&>(s_const);
    auto& t = const_cast<S&>(t_const);
    auto& mapping = const_cast<function<S(F, S)>&>(mapping_const);
    auto& composition = const_cast<function<F(F, F)>&>(composition_const);
    return DiscreteLogarithm::discreteLog<S, F>(f, s, t, mapping, composition, maxSearch, (shared_ptr<typename Hash::template Strategy<S>>){});
}

template <class S, class F>
long long DiscreteLogarithm::discreteLog(const F& f_const, const S& s_const, const S& t_const, const function<S(F, S)>& mapping_const, const function<F(F, F)>& composition_const, long long maxSearch, const shared_ptr<typename Hash::template Strategy<S>>& strategy_const) {
    auto& f = const_cast<F&>(f_const);
    auto& s = const_cast<S&>(s_const);
    auto& t = const_cast<S&>(t_const);
    auto& mapping = const_cast<function<S(F, S)>&>(mapping_const);
    auto& composition = const_cast<function<F(F, F)>&>(composition_const);
    shared_ptr<typename Hash::template Strategy<S>> strategy = strategy_const;
    bool match = ((jisNull(strategy)) ? (s == t) : strategy->equals(s, t));
    if (match) {
        return 0;
    }
    if ((maxSearch <= 0)) {
        return (-1);
    }
    int giantStride = static_cast<int>(std::ceil(std::sqrt(maxSearch)));
    if ((giantStride <= 0)) {
        return (match ? 0 : (-1));
    }
    F giant = f;
    F tmp = f;
    for (int n = (giantStride - 1); (n > 0); (n >>= 1)) {
        if (((n & 1) == 1)) {
            (giant = composition(giant, tmp));
        }
        (tmp = composition(tmp, tmp));
    }
    return DiscreteLogarithm::discreteLog<S, F>(f, giant, s, t, mapping, maxSearch, giantStride, strategy);
}

long long Permutation::inversion(const vector<int>& a_const) {
    auto& a = const_cast<vector<int>&>(a_const);
    int n = static_cast<int>(a.size());
    shared_ptr<struct SegTree<long long>> tree = make_shared<struct SegTree<long long>>(n, [](auto&&... args) { return JLong::sum(std::forward<decltype(args)>(args)...); }, 0LL);
    long long ans = 0;
    for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
        (ans += tree->fold((a[i] + 1), n));
        tree->set(a[i], 1LL);
    }
    return ans;
}

int Main::cost(int i0, int v0, int i1, int v1) {
    int d0 = std::abs((i0 - v1));
    int d1 = std::abs((i1 - v0));
    return (d0 + d1);
}

long long Main::eval(const vector<int>& A_const, const vector<vector<char>>& S_const) {
    auto& A = const_cast<vector<int>&>(A_const);
    auto& S = const_cast<vector<vector<char>>&>(S_const);
    int N = static_cast<int>(S.size());
    vector<int> B = vector<int>((4 * N));
    vector<int> di = vector<int>{1, 0, (-1), 0};
    vector<int> dj = vector<int>{0, (-1), 0, 1};
    for (int t = 0; (t < static_cast<int>(A.size())); (t++)) {
        int dir = (t / N);
        int i;
        int j;
        if ((t < N)) {
            (i = 0);
            (j = t);
        } else {
            if ((t < (2 * N))) {
                (i = (t % N));
                (j = (N - 1));
            } else {
                if ((t < (3 * N))) {
                    (i = (N - 1));
                    (j = ((N - 1) - (t % N)));
                } else {
                    (i = ((N - 1) - (t % N)));
                    (j = 0);
                }
            }
        }
        while (true) {
            if ((S[i][j] == '1')) {
                if ((dir == 0)) {
                    (dir = 1);
                } else {
                    if ((dir == 1)) {
                        (dir = 0);
                    } else {
                        if ((dir == 2)) {
                            (dir = 3);
                        } else {
                            if ((dir == 3)) {
                                (dir = 2);
                            }
                        }
                    }
                }
            } else {
                if ((S[i][j] == '2')) {
                    if ((dir == 0)) {
                        (dir = 3);
                    } else {
                        if ((dir == 3)) {
                            (dir = 0);
                        } else {
                            if ((dir == 2)) {
                                (dir = 1);
                            } else {
                                if ((dir == 1)) {
                                    (dir = 2);
                                }
                            }
                        }
                    }
                }
            }
            (i += di[dir]);
            (j += dj[dir]);
            if ((!((((0 <= i) && (i < N)) && (0 <= j)) && (j < N)))) {
                if ((i == (-1))) {
                    (B[j] = A[t]);
                } else {
                    if ((i == N)) {
                        (B[(((3 * N) - 1) - j)] = A[t]);
                    } else {
                        if ((j == (-1))) {
                            (B[(((4 * N) - 1) - i)] = A[t]);
                        } else {
                            if ((j == N)) {
                                (B[(N + i)] = A[t]);
                            }
                        }
                    }
                }
                break;
            }
        }
    }
    return Permutation::inversion(B);
}

void Main::javaMain(const vector<JString>& args_const) {
    auto& args = const_cast<vector<JString>&>(args_const);
    make_shared<struct Main>()->run();
    MyPrintWriter::getInstance()->flush();
}

void Main::run() {
    shared_ptr<struct FastScanner> sc = FastScanner::getInstance();
    shared_ptr<struct MyPrintWriter> pw = MyPrintWriter::getInstance();
    int N = sc->nextInt();
    vector<int> A = sc->nextInts((4 * N));
    long long startTime = System::nanoTime();
    ArrayUtils::decrementAll(A);
    vector<vector<char>> S = vector<vector<char>>(N, vector<char>(N));
    ArrayUtils::fill(S, '0');
    shared_ptr<struct MinimumCostFlow> mf = make_shared<struct MinimumCostFlow>(((4 * N) + 2));
    for (int i = 0; (i < N); (i++)) {
        mf->addEdge(i, (((3 * N) - 1) - i), this->cost(i, A[i], (((3 * N) - 1) - i), A[(((3 * N) - 1) - i)]), 1);
    }
    for (int i = 0; (i < N); (i++)) {
        for (int j = N; (j < (4 * N)); (j++)) {
            if ((((2 * N) <= j) && (j < (3 * N)))) {
                continue;
            }
            mf->addEdge(i, j, this->cost(i, A[i], j, A[j]), 1);
        }
    }
    int source = (4 * N);
    int sink = (source + 1);
    for (int i = 0; (i < N); (i++)) {
        mf->addFixedFlowEdge(source, i, 0, 1);
    }
    for (int i = N; (i < (4 * N)); (i++)) {
        mf->addEdge(i, sink, 0, 1);
    }
    mf->minCostFlowAtMost(source, sink, N);
    for (int i = 0; (i < N); (i++)) {
        for (auto e : mf->g[i]) {
            if ((e->flow > 0)) {
                if (((N <= e->to) && (e->to < (2 * N)))) {
                    (S[(e->to - N)][i] = '2');
                }
                if ((((3 * N) <= e->to) && (e->to < (4 * N)))) {
                    (S[((N - 1) - (e->to - (3 * N)))][i] = '1');
                }
            }
        }
    }
    long long TL = ((1900LL * 1000) * 1000);
    long long curScore = this->eval(A, S);
    for (int T = 0; (T < 1000000); (T++)) {
        if (((T % 100) == 0)) {
            long long dt = (System::nanoTime() - startTime);
            if ((dt >= TL)) {
                break;
            }
        }
        int i = this->rnd.nextInt(N);
        int j = this->rnd.nextInt(N);
        int v = this->rnd.nextInt(3);
        if (((S[i][j] - '0') == v)) {
            continue;
        }
        char pre = S[i][j];
        (S[i][j] = static_cast<char>(('0' + v)));
        long long score = this->eval(A, S);
        if ((score > curScore)) {
            (S[i][j] = pre);
        } else {
            (curScore = score);
        }
    }
    pw->println(S);
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << setprecision(16);
    Main::javaMain({});
    return 0;
}
0