#include using namespace std; template struct jhas_key : false_type {}; template struct jhas_key()->key)>> : true_type {}; template struct jhas_key_obj : false_type {}; template struct jhas_key().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(v)), is_fp(false) {} JNumber(int v) : l_val(v), d_val(v), is_fp(false) {} JNumber(double v) : l_val(static_cast(v)), d_val(v), is_fp(true) {} JNumber(float v) : l_val(static_cast(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(&obj)) { l_val = *p; d_val = *p; is_fp = false; } else if (auto p = std::any_cast(&obj)) { l_val = *p; d_val = *p; is_fp = false; } else if (auto p = std::any_cast(&obj)) { d_val = *p; l_val = static_cast(*p); is_fp = true; } else if (auto p = std::any_cast(&obj)) { d_val = *p; l_val = static_cast(*p); is_fp = true; } } long long longValue() const { return is_fp ? static_cast(d_val) : l_val; } int intValue() const { return static_cast(longValue()); } double doubleValue() const { return is_fp ? d_val : static_cast(l_val); } float floatValue() const { return static_cast(doubleValue()); } int8_t byteValue() const { return static_cast(longValue()); } int16_t shortValue() const { return static_cast(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 bool jisInstance(const JObject& x) { return x.has_value() && (x.type() == typeid(T) || std::any_cast(&x) != nullptr); } template bool jisInstance(const JObject& x, T& out) { if (x.has_value()) { if (auto p = std::any_cast(&x)) { out = *p; return true; } } return false; } // 未テスト // 計算量: O(1) template struct jpointer_element { using type = T; }; template struct jpointer_element> { using type = T; }; template using jpointer_element_t = typename jpointer_element::type; template bool jisInstance(const std::shared_ptr& x) { using Target = jpointer_element_t; if constexpr (std::is_base_of_v) { return x != nullptr; } else if constexpr (std::is_polymorphic_v && (std::is_polymorphic_v || std::is_base_of_v)) { return std::dynamic_pointer_cast(x) != nullptr; } else { return false; } } // 未テスト // 計算量: O(1) template bool jisInstance(const std::shared_ptr&, T&) { return false; } // 未テスト // 計算量: O(1) template bool jisInstance(const U& x) { if constexpr (std::is_same_v || std::is_base_of_v) return true; else return false; } // 未テスト // 計算量: O(1) template bool jisInstance(const U& x, T& out) { if constexpr (std::is_same_v || std::is_convertible_v) { out = x; return true; } else { return false; } } // 未テスト // 計算量: O(1) template bool jisInstance(const std::shared_ptr& x, std::shared_ptr& out) { if constexpr (std::is_base_of_v) { if (x != nullptr) { out = std::static_pointer_cast(x); return true; } return false; } else if constexpr (std::is_polymorphic_v && (std::is_polymorphic_v || std::is_base_of_v)) { if (auto p = std::dynamic_pointer_cast(x)) { out = p; return true; } return false; } else { return false; } } // 未テスト // 計算量: O(1) template Target jcast(Source&& src) { using CleanTarget = std::decay_t; using CleanSource = std::decay_t; if constexpr (std::is_convertible_v) { return static_cast(std::forward(src)); } else if constexpr (std::is_constructible_v) { return CleanTarget(std::forward(src)); } else { return CleanTarget{}; } } inline std::vector::reference operator^=(std::vector::reference ref, bool val) { ref = ref ^ val; return ref; } inline std::vector::reference operator&=(std::vector::reference ref, bool val) { ref = ref & val; return ref; } inline std::vector::reference operator|=(std::vector::reference ref, bool val) { ref = ref | val; return ref; } inline bool operator==(std::vector::reference a, std::vector::reference b) { return bool(a) == bool(b); } inline bool operator!=(std::vector::reference a, std::vector::reference b) { return bool(a) != bool(b); } inline bool operator==(std::vector::reference a, bool b) { return bool(a) == b; } inline bool operator!=(std::vector::reference a, bool b) { return bool(a) != b; } inline bool operator==(bool a, std::vector::reference b) { return a == bool(b); } inline bool operator!=(bool a, std::vector::reference b) { return a != bool(b); } template struct JOptionalVal; template struct NullableVal : public std::optional { using std::optional::optional; NullableVal() : std::optional(std::nullopt) {} NullableVal(const std::optional& o) : std::optional(o) {} NullableVal(std::nullptr_t) : std::optional(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& o) const { return static_cast&>(*this) == static_cast&>(o); } bool operator!=(const NullableVal& o) const { return !(*this == o); } }; template struct jis_nullable_val : std::false_type {}; template struct jis_nullable_val> : std::true_type {}; template struct jis_optional : std::false_type {}; template struct jis_optional> : std::true_type {}; template struct jis_optional> : std::true_type {}; template struct jis_std_function : std::false_type {}; template struct jis_std_function> : std::true_type {}; template struct Nullable { using type = std::conditional_t, NullableVal, T>; }; // 未テスト // 計算量: O(1) template bool jisNull(const T& x) { return false; } template bool jisNull(const NullableVal& x) { return !x.has_value(); } template bool jisNull(const std::optional& x) { return !x.has_value(); } template bool jisNull(const vector& x) { return x.empty(); } template bool jisNull(const shared_ptr& x) { return !x; } inline bool jisNull(const JObject& x) { return !x.has_value(); } template inline bool jisNull(const std::function& f) { return !f; } // 未テスト // 計算量: O(1) template, JObject> || is_same_v, JObject>) && !(is_same_v, JObject> && is_same_v, JObject>)>> bool operator==(const T& a, const U& b) { if constexpr (is_same_v, JObject>) { if (!b.has_value()) return jisNull(a); return false; } else { return b == a; } } template, JObject> || is_same_v, JObject>) && !(is_same_v, JObject> && is_same_v, JObject>)>> bool operator!=(const T& a, const U& b) { return !(a == b); } template struct JEntry { std::shared_ptr> ptr; JEntry() : ptr(nullptr) {} JEntry(std::nullptr_t) : ptr(nullptr) {} JEntry(const std::pair& p) : ptr(std::make_shared>(p)) {} JEntry(std::pair&& p) : ptr(std::make_shared>(std::move(p))) {} JEntry(const std::pair& p) : ptr(std::make_shared>(p.first, p.second)) {} JEntry(std::shared_ptr> p) : ptr(std::move(p)) {} std::pair& operator*() { return *ptr; } const std::pair& operator*() const { return *ptr; } std::pair* operator->() { return ptr.get(); } const std::pair* 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&() { return *ptr; } operator const std::pair&() 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 inline bool jisNull(const JEntry& e) { return e.ptr == nullptr; } template struct jis_pointer_like : std::false_type {}; template struct jis_pointer_like().operator->())>> : std::true_type {}; // 未テスト // 計算量: O(1) template decltype(auto) jentryKey(T&& t) { if constexpr (jis_pointer_like>::value) { return (t->first); } else { return (t.first); } } // 未テスト // 計算量: O(1) template decltype(auto) jentryValue(T&& t) { if constexpr (jis_pointer_like>::value) { return (t->second); } else { return (t.second); } } // 未テスト // 計算量: O(1) template decltype(auto) jentrySetValue(T&& t, V&& v) { if constexpr (jis_pointer_like>::value) { return (t->second = std::forward(v)); } else { return (t.second = std::forward(v)); } } // 未テスト // 計算量: O(N) template void jassign(Dst& dst, Src&& src) { if constexpr (std::is_assignable_v) { dst = std::forward(src); } else if constexpr (std::is_constructible_v) { dst = Dst(std::forward(src)); } else { dst.clear(); for (const auto& item : src) { typename Dst::value_type v; jassign(v, item); dst.push_back(v); } } } template struct JOptionalVal { std::optional opt; JOptionalVal() : opt(std::nullopt) {} JOptionalVal(nullptr_t) : opt(std::nullopt) {} JOptionalVal(const T& val) : opt(val) {} JOptionalVal(const std::optional& 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>> operator U() const { return opt.value_or(U{}); } operator bool() const { if constexpr (std::is_same_v) { 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 inline bool jisNull(const JOptionalVal& x) { return !x.has_value(); } struct JStringTokenizer; inline bool jisNull(const JStringTokenizer& x); template struct jhas_ostream : false_type {}; template struct jhas_ostream() << declval())>> : true_type {}; template struct jhas_toString : false_type {}; template struct jhas_toString().toString())>> : true_type {}; template struct jhas_ptr_toString : false_type {}; template struct jhas_ptr_toString()->toString())>> : true_type {}; template string jstr(const T& x); // 未テスト // 計算量: O(|a|) inline string jstr(const vector& a) { return string(a.begin(), a.end()); } // 未テスト // 計算量: O(|a| * len(jstr(elem))) template string jstr(const vector& 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::infinity()) return "Infinity"; if (x == -numeric_limits::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 string jstr(const T& x) { if constexpr (is_same_v, JObject>) { if (!x.has_value()) return "null"; if (auto p = std::any_cast(&x)) return std::to_string(*p); if (auto p = std::any_cast(&x)) return std::to_string(*p); if (auto p = std::any_cast(&x)) return jdouble_to_string(*p); if (auto p = std::any_cast(&x)) return *p; return ""; } else if constexpr (jhas_toString::value) { return x.toString(); } else if constexpr (jhas_ptr_toString::value) { return x ? x->toString() : "null"; } else if constexpr (jhas_ostream::value) { if constexpr (is_floating_point_v>) { return jdouble_to_string(static_cast(x)); } else { ostringstream o; o << x; return o.str(); } } else { return ""; } } template 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(s[start]))) ++start; size_t end = s.size(); while (end > start && ::isspace(static_cast(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(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(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(c))) return false; } return true; } // 未テスト // 計算量: O(sum |elements|) inline JString jjoin(const JString& delimiter, const vector& 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 inline JString jjoin(const JString& delimiter, const Args&... args) { vector elements{jstr(args)...}; return jjoin(delimiter, elements); } inline vector jchars(const JString& s) { return vector(s.begin(), s.end()); } inline char jtoUpperCase(char c) { return static_cast(::toupper(static_cast(c))); } inline JString jtoUpperCase(JString s) { for (char& c : s) c = static_cast(::toupper(static_cast(c))); return s; } inline char jtoLowerCase(char c) { return static_cast(::tolower(static_cast(c))); } inline JString jtoLowerCase(JString s) { for (char& c : s) c = static_cast(::tolower(static_cast(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(a[i])) != ::tolower(static_cast(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 jsplit(const JString& s, const JString& regex) { vector 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::system_clock::now().time_since_epoch()).count(); } // 未テスト // 計算量: O(1) inline long long jnanoTime() { return chrono::duration_cast(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 struct jhas_compareTo : false_type {}; template struct jhas_compareTo().compareTo(declval()))>> : true_type {}; template struct jhas_ptr_compareTo : false_type {}; template struct jhas_ptr_compareTo()->compareTo(declval()))>> : true_type {}; template struct jhas_equals : false_type {}; template struct jhas_equals().equals(declval()))>> : true_type {}; template struct jhas_ptr_equals : false_type {}; template struct jhas_ptr_equals()->equals(declval()))>> : true_type {}; // 未テスト // 計算量: O(1) template bool jequals(const A& a, const B& b) { if constexpr (is_same_v, decay_t>) { if constexpr (jis_std_function>::value) { if (!a && !b) return true; if (!a || !b) return false; return a.target_type() == b.target_type(); } else if constexpr (jhas_ptr_equals::value) { if (a == b) return true; if (a && b) return a->equals(b); return false; } else if constexpr (jhas_equals::value) { return a.equals(b); } else if constexpr (jhas_ptr_compareTo::value) { if (a == b) return true; if (a && b) return a->compareTo(b) == 0; return false; } else if constexpr (jhas_compareTo::value) { return a.compareTo(b) == 0; } else { return a == b; } } else if constexpr (is_convertible_v) { return a == static_cast(b); } else if constexpr (is_convertible_v) { return static_cast(a) == b; } else { return false; } } template int jcompareTo(const A& a, const B& b) { if constexpr (jhas_ptr_compareTo::value) { return a->compareTo(b); } else if constexpr (jhas_compareTo::value) { return a.compareTo(b); } else { return (a > b) - (a < b); } } template struct JComparator { F key; template int operator()(const T& a, const T& b) const { if constexpr (is_invocable_v) { return key(a, b); } else { auto x = key(a), y = key(b); return jcompareTo(x, y); } } template auto thenComparing(G other) const; template auto thenComparingInt(G key) const { return thenComparing(key); } template auto thenComparingLong(G key) const { return thenComparing(key); } template auto thenComparingDouble(G key) const { return thenComparing(key); } }; template struct JChainedComparator { A first; B second; template int operator()(const T& a, const T& b) const { int result = first(a, b); return result != 0 ? result : second(a, b); } template auto thenComparing(G other) const; template auto thenComparingInt(G key) const { return thenComparing(key); } template auto thenComparingLong(G key) const { return thenComparing(key); } template auto thenComparingDouble(G key) const { return thenComparing(key); } }; template template auto JComparator::thenComparing(G other) const { return JChainedComparator, JComparator>{*this, JComparator{other}}; } template template auto JChainedComparator::thenComparing(G other) const { return JChainedComparator, JComparator>{*this, JComparator{other}}; } template struct jis_jcomparator : false_type {}; template struct jis_jcomparator> : true_type {}; template struct jis_jcomparator> : true_type {}; template auto jcomparing(F key) { if constexpr (jis_jcomparator>::value) { return key; } else { return JComparator{key}; } } // 未テスト // 計算量: O(1) template auto jreversed(F cmp) { return [cmp = std::move(cmp)](const auto& a, const auto& b) { return cmp(b, a); }; } // 未テスト // 計算量: O(1) template struct JLess { bool operator()(const T& a, const T& b) const { if constexpr (is_same_v, 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(&a)) return *pa < std::any_cast(b); if (auto pa = std::any_cast(&a)) return *pa < std::any_cast(b); if (auto pa = std::any_cast(&a)) return *pa < std::any_cast(b); return false; } else if constexpr (jhas_ptr_compareTo::value) { return a->compareTo(b) < 0; } else if constexpr (jhas_compareTo::value) { return a.compareTo(b) < 0; } else { return a < b; } } }; struct { template bool operator()(const A& a, const B& b) const { return JLess>{}(a, b); } } jless_fn; template void jsort(vector& a) { stable_sort(a.begin(), a.end(), jless_fn); } template void jsort(vector& a, C compare) { if constexpr (is_same_v, nullptr_t>) { stable_sort(a.begin(), a.end(), jless_fn); } else { using R = invoke_result_t; stable_sort(a.begin(), a.end(), [&](const T& x, const T& y) { if constexpr (is_same_v) return compare(x, y); else return compare(x, y) < 0; }); } } // 未テスト // 計算量: O(N log N) template void jsort(vector& a, int fromIndex, int toIndex) { stable_sort(a.begin() + fromIndex, a.begin() + toIndex, jless_fn); } // 未テスト // 計算量: O(N log N) template void jsort(vector& a, int fromIndex, int toIndex, C compare) { if constexpr (is_same_v, nullptr_t>) { stable_sort(a.begin() + fromIndex, a.begin() + toIndex, jless_fn); } else { using R = invoke_result_t; stable_sort(a.begin() + fromIndex, a.begin() + toIndex, [&](const T& x, const T& y) { if constexpr (is_same_v) return compare(x, y); else return compare(x, y) < 0; }); } } // 未テスト // 計算量: O(N) template void jfill(vector& a, const U& x) { if constexpr (is_same_v, nullptr_t> && !is_pointer_v && !is_same_v && !is_same_v) { if constexpr (is_default_constructible_v) { fill(a.begin(), a.end(), T{}); } else { fill(a.begin(), a.end(), static_cast(x)); } } else { fill(a.begin(), a.end(), static_cast(x)); } } // 未テスト // 計算量: O(toIndex - fromIndex) template void jfill(vector& a, int fromIndex, int toIndex, const U& x) { if constexpr (is_same_v, nullptr_t> && !is_pointer_v && !is_same_v && !is_same_v) { if constexpr (is_default_constructible_v) { fill(a.begin() + fromIndex, a.begin() + toIndex, T{}); } else { fill(a.begin() + fromIndex, a.begin() + toIndex, static_cast(x)); } } else { fill(a.begin() + fromIndex, a.begin() + toIndex, static_cast(x)); } } template vector jcopyOf(const vector& a, int n) { vector result(n); copy_n(a.begin(), min(a.size(), n), result.begin()); return result; } template vector jcopyOfRange(const vector& a, int from, int to) { vector result(max(0, to - from)); int count = max(0, min(a.size(), to) - from); if (count > 0) copy_n(a.begin() + from, count, result.begin()); return result; } template void jarraycopy(const vector& src, int srcPos, vector& dst, int dstPos, int length) { copy_n(src.begin() + srcPos, length, dst.begin() + dstPos); } template void jsetAll(vector& a, F f) { for (int i = 0; i < (int)a.size(); ++i) a[i] = f(i); } // 未テスト // 計算量: O(N) template void jparallelSetAll(vector& a, F f) { jsetAll(a, f); } // 未テスト // 計算量: O(min(N, M)) template 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 int jcompare(const vector& a, int aFrom, int aTo, const vector& 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 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 int jcompare(const vector& a, int aFrom, int aTo, const vector& 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 void jparallelPrefix(vector& a, F op) { for (size_t i = 1; i < a.size(); ++i) a[i] = op(a[i - 1], a[i]); } template void jparallelPrefix(vector& a, int from, int to, F op) { for (int i = from + 1; i < to; ++i) a[i] = op(a[i - 1], a[i]); } template 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 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 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 buffer; size_t pos = 0; size_t marked_pos = 0; bool is_bytes = false; JInputStream() = default; JInputStream(const vector& b) : buffer(b), is_bytes(true) {} JInputStream(const vector& b) : buffer(b.begin(), b.end()), is_bytes(true) {} template 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(buffer[pos++]); } if (is_bytes) return -1; int ch = cin.get(); if (ch == EOF) return -1; buffer.push_back(static_cast(ch)); pos++; return ch; } int read(vector& b) { return read(b, 0, static_cast(b.size())); } int read(vector& b) { return read(b, 0, static_cast(b.size())); } template int read(vector& 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(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(buffer.size()) - static_cast(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(ch)); } return s; } }; size_t jhash() { return 1; } // 未テスト // 計算量: O(1) template size_t jhashValue(const pair& p); template struct jhas_hash_code : false_type {}; template struct jhas_hash_code().hashCode())>> : true_type {}; template struct jhas_begin_end_range : false_type {}; template struct jhas_begin_end_range().begin()), decltype(declval().end())>> : true_type {}; template size_t jhashValue(const T& x) { if constexpr (is_same_v, JObject>) { return x.has_value() ? 1 : 0; } else if constexpr (jis_std_function>::value) { return x ? 1 : 0; } else if constexpr (jis_nullable_val>::value || jis_optional>::value) { return x.has_value() ? jhashValue(*x) : 0; } else if constexpr (jhas_hash_code>::value) { return static_cast(x.hashCode()); } else if constexpr (jhas_begin_end_range>::value) { size_t result = 0; for (const auto& item : x) { result += jhashValue(item); } return result; } else { return hash{}(x); } } // 未テスト // 計算量: O(1) template size_t jhashValue(const pair& p) { return jhashValue(p.first) ^ jhashValue(p.second); } template size_t jhashValue(const vector& values) { size_t result = 1; for (const auto& value : values) result = result * 31 + jhashValue(value); return result; } template size_t jhash(const T& x, const U&... rest) { return jhashValue(x) * 31 + jhash(rest...); } inline void jnoop() {} inline void jprint() {} template void jprint(const T& x, const U&... rest) { cout << jstr(x); jprint(rest...); } inline void jprintln() { cout << '\n'; } template void jprintln(const T& x, const U&... rest) { cout << jstr(x); jprint(rest...); cout << '\n'; } template void jprintf(const char* fmt, Args&&... args) { printf(fmt, forward(args)...); } template void jprintf(const JString& fmt, Args&&... args) { printf(fmt.c_str(), forward(args)...); } // 未テスト // 計算量: O(1) inline void jeprint() {} template void jeprint(const T& x, const U&... rest) { cerr << jstr(x); jeprint(rest...); } inline void jeprintln() { cerr << '\n'; } template void jeprintln(const T& x, const U&... rest) { cerr << jstr(x); jeprint(rest...); cerr << '\n'; } template void jeprintf(const char* fmt, Args&&... args) { fprintf(stderr, fmt, forward(args)...); } template void jeprintf(const JString& fmt, Args&&... args) { fprintf(stderr, fmt.c_str(), forward(args)...); } template JString jformat(const char* fmt, Args&&... args) { int sz = snprintf(nullptr, 0, fmt, forward(args)...); if (sz <= 0) return ""; vector buf(sz + 1); snprintf(buf.data(), buf.size(), fmt, forward(args)...); return JString(buf.data(), sz); } template JString jformat(const JString& fmt, Args&&... args) { return jformat(fmt.c_str(), forward(args)...); } template typename enable_if && !is_convertible_v, JString>::type jformat(const L&, const char* fmt, Args&&... args) { return jformat(fmt, forward(args)...); } template typename enable_if && !is_convertible_v, JString>::type jformat(const L&, const JString& fmt, Args&&... args) { return jformat(fmt.c_str(), forward(args)...); } template auto jsignum(T x) { if constexpr (std::is_floating_point_v) { 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 auto jmin(const A& a, const B& b) { using C = common_type_t; if constexpr (std::is_floating_point_v) { if (std::isnan(a) || std::isnan(b)) return std::numeric_limits::quiet_NaN(); } return std::min(a, b); } template auto jmax(const A& a, const B& b) { using C = common_type_t; if constexpr (std::is_floating_point_v) { if (std::isnan(a) || std::isnan(b)) return std::numeric_limits::quiet_NaN(); } return std::max(a, b); } // 未テスト // 計算量: O(1) template auto jround(T x) { if constexpr (std::is_same_v, float>) { return static_cast(std::floor(x + 0.5f)); } else { return static_cast(std::floor(x + 0.5)); } } template auto jfloorDiv(A a, B b) { using C = common_type_t; C x = a, y = b; C res = x / y; C rem = x % y; if ((rem != 0) && ((x ^ y) < 0)) --res; return res; } template auto jceilDiv(A a, B b) { using C = common_type_t; C x = a, y = b; C res = x / y; C rem = x % y; if ((rem != 0) && ((x ^ y) > 0)) ++res; return res; } template auto jfloorMod(A a, B b) { using C = common_type_t; C x = a, y = b; C rem = x % y; if ((rem != 0) && ((x ^ y) < 0)) rem += y; return rem; } // 未テスト // 計算量: O(1) template auto jusr(T a, U b) { using UT = std::make_unsigned_t; return static_cast(static_cast(a) >> b); } template auto jclamp(V v, L l, H h) { return v < l ? l : (v > h ? h : v); } template auto jaddExact(A a, B b) { return a + b; } template auto jsubtractExact(A a, B b) { return a - b; } template auto jmultiplyExact(A a, B b) { return a * b; } template auto jtoIntExact(T x) { return static_cast(x); } template auto jnegateExact(T x) { return -x; } // 未テスト // 計算量: O(1) template auto jabsExact(T x) { return x < 0 ? -x : x; } // 未テスト // 計算量: O(1) template auto jincrementExact(T a) { return a + 1; } // 未テスト // 計算量: O(1) template auto jdecrementExact(T a) { return a - 1; } // 未テスト // 計算量: O(1) inline long long jmultiplyFull(int x, int y) { return static_cast(x) * y; } // 未テスト // 計算量: O(1) inline long long jmultiplyHigh(long long x, long long y) { return static_cast((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 int jcompareValue(const A& a, const B& b) { return (a > b) - (a < b); } template int jcompare(const vector& a, const vector& 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 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(val); } int getAsInt() const { return static_cast(val); } double getAsDouble() const { return static_cast(val); } T orElse(T def) const { return has ? val : def; } // 未テスト // 計算量: O(1) template 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 void ifPresent(F action) const { if (has) action(val); } // 未テスト // 計算量: O(f) // map: JOptional x (T -> U) -> JOptional template auto map(F f) const -> JOptional { if (!has) return JOptional{false, {}}; return JOptional{true, f(val)}; } // 未テスト // 計算量: O(f) // flatMap: JOptional x (T -> JOptional) -> JOptional template auto flatMap(F f) const -> decltype(f(val)) { if (!has) return decltype(f(val)){false, {}}; return f(val); } }; // 任意の JOptional へ暗黙変換できる空値センチネル型。 // 計算量: O(1) struct JOptionalEmpty { template operator JOptional() const { return JOptional{false, {}}; } }; struct Optional { // 未テスト // 計算量: O(1) template static JOptional of(T v) { return JOptional{true, v}; } // 未テスト // 計算量: O(1) template static JOptional ofNullable(T v) { return JOptional{!jisNull(v), v}; } // 未テスト // 計算量: O(1) // empty() は任意の JOptional へ暗黙変換できる JOptionalEmpty を返す。 static JOptionalEmpty empty() { return JOptionalEmpty{}; } }; struct OptionalLong { // 未テスト // 計算量: O(1) static JOptional of(long long v) { return JOptional{true, v}; } // 未テスト // 計算量: O(1) static JOptionalEmpty empty() { return JOptionalEmpty{}; } }; struct OptionalInt { // 未テスト // 計算量: O(1) static JOptional of(int v) { return JOptional{true, v}; } // 未テスト // 計算量: O(1) static JOptionalEmpty empty() { return JOptionalEmpty{}; } }; struct OptionalDouble { // 未テスト // 計算量: O(1) static JOptional of(double v) { return JOptional{true, v}; } // 未テスト // 計算量: O(1) static JOptionalEmpty empty() { return JOptionalEmpty{}; } }; template struct JStream; inline vector jlistOf() { return {}; } template auto jlistOf(const vector& v) { return v; } template auto jlistOf(T first, U... rest) { using V = common_type_t; return vector{static_cast(first), static_cast(rest)...}; } template struct JList : vector { JList() = default; explicit JList(size_t initialCapacity) { this->reserve(initialCapacity); } JList(size_t count, const T& value) : vector(count, value) {} JList(const vector& source) : vector(source) {} JList(vector&& source) : vector(move(source)) {} template JList(const JList& source) { for (const auto& value : source) { if constexpr (is_same_v) this->push_back(any_cast(value)); else this->push_back(static_cast(value)); } } template::value_type> JList(Iter first, Iter last) : vector(first, last) {} template && !is_same_v, JList> && !is_same_v, vector>>> JList(const Container& container) { for (const auto& item : container) { if constexpr (is_same_v, JObject>) this->push_back(any_cast(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::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 bool remove(const Arg& x) { if constexpr (is_integral_v && !is_same_v, bool>) { if constexpr (is_integral_v && !is_same_v, bool>) { auto it = std::find(this->begin(), this->end(), static_cast(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) return jequals(item, x); else if constexpr (jhas_key::value) return item->key == x; else if constexpr (jhas_key_obj::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) return jequals(item, x); else if constexpr (jhas_key::value) return item->key == x; else if constexpr (jhas_key_obj::value) return item.key == x; else return false; }); if (it != this->end()) { this->erase(it); return true; } return false; } } template bool addAll(const C& c) { for (const auto& x : c) this->push_back(x); return true; } // 未テスト // 計算量: O(N + M) template 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 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 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 bool containsAll(const C& c) const { for (const auto& x : c) { if (!this->contains(x)) return false; } return true; } // 未テスト // 計算量: O(N) template void replaceAll(F operator_fn) { for (auto& item : *this) item = operator_fn(item); } template bool contains(const Arg& x) const { return std::find_if(this->begin(), this->end(), [&](const T& item) { return jequals(item, x); }) != this->end(); } template 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 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 void sort(Comp comp) { if constexpr (is_same_v, nullptr_t>) { std::stable_sort(this->begin(), this->end(), jless_fn); } else { using R = invoke_result_t; std::stable_sort(this->begin(), this->end(), [&](const auto& a, const auto& b) { if constexpr (is_same_v) 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 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{}; return JList(this->begin() + fromIndex, this->begin() + toIndex); } auto stream() const { return JStream(*this); } }; struct JArray { template static vector newInstance(const std::type_info&, int length) { return vector(length); } template static vector newInstance(const T&, int length) { return vector(length); } template static int getLength(const vector& v) { return static_cast(v.size()); } static int getLength(const JObject& obj) { if (!obj.has_value()) return 0; try { return static_cast(std::any_cast>(obj).size()); } catch(...) {} try { return static_cast(std::any_cast>(obj).size()); } catch(...) {} try { return static_cast(std::any_cast>(obj).size()); } catch(...) {} return 0; } template static auto get(const vector& v, int index) { return v[index]; } static JObject get(const JObject& obj, int index) { try { return std::any_cast>(obj)[index]; } catch(...) {} try { return std::any_cast>(obj)[index]; } catch(...) {} try { return std::any_cast>(obj)[index]; } catch(...) {} return {}; } }; using Array = JArray; template auto jtoArray(const C& values) { using T = typename C::value_type; return vector(values.begin(), values.end()); } template struct JPriorityQueue { function comp = [](const T& a, const T& b) { return jcompareTo(a, b); }; vector 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(data.size()) / 2) - 1; i >= 0; --i) { T item = std::move(data[i]); siftDown(static_cast(i), std::move(item)); } } JPriorityQueue() = default; template>> explicit JPriorityQueue(C c) : comp([c](const T& a, const T& b) { return c(a, b); }) {} template>> JPriorityQueue(int, C c) : comp([c](const T& a, const T& b) { return c(a, b); }) {} explicit JPriorityQueue(int) {} // 未テスト // 計算量: O(|c|) template && !is_same_v, JPriorityQueue> && !is_invocable_v>> explicit JPriorityQueue(const Container& c) { for (const auto& item : c) { if constexpr (is_same_v, JObject>) data.push_back(any_cast(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 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 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 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, JInputStream>>> explicit JPrintWriter(const StreamType&) {} explicit JPrintWriter(nullptr_t) {} template void print(const T& x) { if (is_err) jeprint(x); else jprint(x); } template void println(const T& x) { if (is_err) jeprintln(x); else jprintln(x); } template void print(const vector& a) { print(a, " "); } template void println(const vector& a) { println(a, " "); } void print(const vector& a) { for (char c : a) print(c); } void println(const vector& a) { for (char c : a) print(c); println(); } template void print(const vector& a, const JString& separator) { for (size_t i = 0; i < a.size(); ++i) { if (i) print(separator); print(a[i]); } } template void println(const vector& 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 void printf(Args&&... args) { if (is_err) jeprintf(forward(args)...); else jprintf(forward(args)...); } template void write(const T& x) { print(x); } void write(int c) { if (is_err) cerr.put(static_cast(c)); else cout.put(static_cast(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::max(); static constexpr long long MIN_VALUE = numeric_limits::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(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(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(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(i); int dist = distance & 63; return static_cast((u << dist) | (u >> ((64 - dist) & 63))); } // 未テスト // 計算量: O(1) static long long rotateRight(long long i, int distance) { uint64_t u = static_cast(i); int dist = distance & 63; return static_cast((u >> dist) | (u << ((64 - dist) & 63))); } // 未テスト // 計算量: O(1) static long long divideUnsigned(long long dividend, long long divisor) { return static_cast(static_cast(dividend) / static_cast(divisor)); } // 未テスト // 計算量: O(1) static long long remainderUnsigned(long long dividend, long long divisor) { return static_cast(static_cast(dividend) % static_cast(divisor)); } // 未テスト // 計算量: O(1) static int compareUnsigned(long long x, long long y) { uint64_t ux = static_cast(x); uint64_t uy = static_cast(y); return (ux > uy) - (ux < uy); } static long long reverse(long long x) { uint64_t u = static_cast(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(u); } static long long reverseBytes(long long x) { return static_cast(__builtin_bswap64(static_cast(x))); } static JString toBinaryString(long long x) { if (x == 0) return "0"; uint64_t u = static_cast(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(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(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(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(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; } }; template 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(engine()); } int nextInt(int bound) const { return uniform_int_distribution(0, bound - 1)(engine); } int nextInt(int origin, int bound) const { return uniform_int_distribution(origin, bound - 1)(engine); } long long nextLong() const { return static_cast(engine()); } long long nextLong(long long bound) const { return uniform_int_distribution(0, bound - 1)(engine); } long long nextLong(long long origin, long long bound) const { return uniform_int_distribution(origin, bound - 1)(engine); } double nextDouble() const { return uniform_real_distribution(0.0, 1.0)(engine); } double nextDouble(double bound) const { return uniform_real_distribution(0.0, bound)(engine); } double nextDouble(double origin, double bound) const { return uniform_real_distribution(origin, bound)(engine); } float nextFloat() const { return uniform_real_distribution(0.0f, 1.0f)(engine); } bool nextBoolean() const { return (engine() & 1) != 0; } // 未テスト // 計算量: O(1) JRandom split() const { return JRandom(static_cast(engine())); } double nextGaussian() const { return normal_distribution(0.0, 1.0)(engine); } }; struct FastScanner; struct MyPrintWriter; struct PopcountBIT; struct Permutation; struct ArrayUtils; struct ArrayUtils2D; struct MinimumCostFlow; struct Main; struct FastScanner : public std::enable_shared_from_this { virtual ~FastScanner() = default; FastScanner(); static shared_ptr getInstance(); virtual bool hasNext(); virtual bool hasNextByte(); virtual bool isPrintableChar(int c); virtual int nextInt(); virtual vector nextInts(int n); virtual long long nextLong(); virtual int readByte(); inline static shared_ptr instance = (shared_ptr){}; JInputStream in = JInputStream(); vector buffer = vector((int)((unsigned int)(1) << 16)); int ptr = 0; int buflen = 0; }; struct MyPrintWriter : public std::enable_shared_from_this, public JPrintWriter { using JPrintWriter::println; virtual ~MyPrintWriter() = default; MyPrintWriter(); MyPrintWriter(const JPrintWriter& out_const); static shared_ptr getInstance(); virtual void println(const vector>& a_const); inline static shared_ptr instance = (shared_ptr){}; }; struct PopcountBIT : public std::enable_shared_from_this { virtual ~PopcountBIT() = default; PopcountBIT(const vector& a_const); PopcountBIT(int n); virtual void flip(int i); virtual bool get(int i); virtual void set(int i, bool v); virtual int sum(int r); int n = {}; int words = {}; vector bits = {}; vector tree = {}; int total = {}; }; struct Permutation : public std::enable_shared_from_this { virtual ~Permutation() = default; Permutation(); static long long inversion(const vector& a_const); }; struct ArrayUtils : public std::enable_shared_from_this { virtual ~ArrayUtils() = default; ArrayUtils(); static int argMax(const vector& a_const); static void decrementAll(const vector& a_const); static void fill(const vector>& a_const, char v); static void fill(const vector& a_const, int v); static void fill(const vector>& a_const, int v); static void fill(const vector>>& a_const, int v); static long long max(const vector& a_const); }; struct ArrayUtils2D : public std::enable_shared_from_this { virtual ~ArrayUtils2D() = default; ArrayUtils2D(); static void fill(const vector>& a_const, char v); static void fill(const vector>& a_const, int v); }; struct MinimumCostFlow : public std::enable_shared_from_this { struct Edge; struct Edge : public std::enable_shared_from_this { 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 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 minCostCirculation(); virtual long long minCostFlowAtMost(int s, int t, long long cap); virtual void updateDistance(int src); int N = {}; vector>> g = {}; vector>> ig = {}; vector excess = {}; vector potential = {}; long long INF = (JLong::MAX_VALUE / 3); vector> incommingShortestPathEdge = {}; vector d = {}; long long base = 0; }; struct Main : public std::enable_shared_from_this
{ struct Result; struct Result : public std::enable_shared_from_this { virtual ~Result() = default; Result(const vector& B_const, int score) { vector B = B_const; (this->B_ = B); (this->score_ = score); } template, Result> && !(is_same_v, vector> && is_same_v, int>)>> Result(F0&& p0, F1&& p1) { jassign(this->B_, std::forward(p0)); jassign(this->score_, std::forward(p1)); } virtual vector B() { return this->B_; } virtual int score() { return this->score_; } vector B_ = {}; int score_ = {}; }; virtual ~Main() = default; Main(); virtual int cost(int i0, int v0, int i1, int v1); virtual shared_ptr eval(const vector& A_const, const vector>& S_const, const vector>>& memo_const); static void javaMain(const vector& args_const); virtual void run(); virtual int trace(const vector>& S_const, const vector>>& memo_const, int N, int t, int mark); inline static JRandom rnd = JRandom(0); inline static vector DI = vector{1, 0, (-1), 0}; inline static vector DJ = vector{0, (-1), 0, 1}; }; FastScanner::FastScanner() { } MyPrintWriter::MyPrintWriter() : JPrintWriter(JPrintWriter()) { } MyPrintWriter::MyPrintWriter(const JPrintWriter& out_const) : JPrintWriter(out_const) { auto& out = const_cast(out_const); } PopcountBIT::PopcountBIT(const vector& a_const) : PopcountBIT(static_cast(a_const.size())) { auto& a = const_cast&>(a_const); for (int i = 0; (i < this->n); (i++)) { if (a[i]) { (this->bits[jusr(i, 6)] |= (1LL << (i & 63))); } } for (int j = 0; (j < this->words); (j++)) { int c = JLong::bitCount(this->bits[j]); (this->total += c); (this->tree[(j + 1)] += c); int p = ((j + 1) + ((j + 1) & (-(j + 1)))); if ((p <= this->words)) { (this->tree[p] += this->tree[(j + 1)]); } } } PopcountBIT::PopcountBIT(int n) { (this->n = n); (this->words = (jusr(n, 6) + 1)); (this->bits = vector(this->words)); (this->tree = vector((this->words + 1))); } Permutation::Permutation() { } ArrayUtils::ArrayUtils() { } ArrayUtils2D::ArrayUtils2D() { } MinimumCostFlow::MinimumCostFlow(int N) { (this->N = N); (this->g = vector>>(this->N)); (this->ig = vector>>(this->N)); (this->excess = vector(this->N)); (this->potential = vector(this->N)); (this->d = vector(this->N)); (this->incommingShortestPathEdge = vector>(this->N)); for (int i = 0; (i < this->N); (++i)) { (this->g[i] = JList>()); (this->ig[i] = JList>()); } } Main::Main() { } shared_ptr FastScanner::getInstance() { if ((jisNull(FastScanner::instance))) { (FastScanner::instance = make_shared()); } 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(this->nextLong()); } vector FastScanner::nextInts(int n) { vector a = vector(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); } } shared_ptr MyPrintWriter::getInstance() { if ((jisNull(MyPrintWriter::instance))) { (MyPrintWriter::instance = make_shared()); } return MyPrintWriter::instance; } void MyPrintWriter::println(const vector>& a_const) { auto& a = const_cast>&>(a_const); for (int i = 0; (i < static_cast(a.size())); (i++)) { this->println(a[i]); } } void PopcountBIT::flip(int i) { int w = jusr(i, 6); long long mask = (1LL << (i & 63)); int d = (((this->bits[w] & mask) == 0) ? 1 : (-1)); (this->bits[w] ^= mask); (this->total += d); for (int x = (w + 1); (x <= this->words); (x += (x & (-x)))) { (this->tree[x] += d); } } bool PopcountBIT::get(int i) { return ((jusr(this->bits[jusr(i, 6)], (i & 63)) & 1LL) != 0); } void PopcountBIT::set(int i, bool v) { if ((this->get(i) == v)) { return; } this->flip(i); } int PopcountBIT::sum(int r) { int w = jusr(r, 6); int s = JLong::bitCount((this->bits[w] & ((1LL << (r & 63)) - 1))); for (int x = w; (x > 0); (x -= (x & (-x)))) { (s += this->tree[x]); } return s; } long long Permutation::inversion(const vector& a_const) { auto& a = const_cast&>(a_const); int n = static_cast(a.size()); shared_ptr tree = make_shared(n); long long ans = 0; for (int i = 0; (i < static_cast(a.size())); (++i)) { (ans += (i - tree->sum(a[i]))); tree->set(a[i], true); } return ans; } int ArrayUtils::argMax(const vector& a_const) { auto& a = const_cast&>(a_const); int ret = 0; for (int i = 0; (i < static_cast(a.size())); (++i)) { if ((a[i] > a[ret])) { (ret = i); } } return ret; } void ArrayUtils::decrementAll(const vector& a_const) { auto& a = const_cast&>(a_const); for (int i = 0; (i < static_cast(a.size())); (i++)) { (a[i]--); } } void ArrayUtils::fill(const vector>& a_const, char v) { auto& a = const_cast>&>(a_const); ArrayUtils2D::fill(a, v); } void ArrayUtils::fill(const vector& a_const, int v) { auto& a = const_cast&>(a_const); jfill(a, v); } void ArrayUtils::fill(const vector>& a_const, int v) { auto& a = const_cast>&>(a_const); ArrayUtils2D::fill(a, v); } void ArrayUtils::fill(const vector>>& a_const, int v) { auto& a = const_cast>>&>(a_const); for (int i = 0; (i < static_cast(a.size())); (++i)) { ArrayUtils::fill(a[i], v); } } long long ArrayUtils::max(const vector& a_const) { auto& a = const_cast&>(a_const); long long ret = JLong::MIN_VALUE; for (int i = 0; (i < static_cast(a.size())); (++i)) { (ret = jmax(ret, a[i])); } return ret; } void ArrayUtils2D::fill(const vector>& a_const, char v) { auto& a = const_cast>&>(a_const); for (int i = 0; (i < static_cast(a.size())); (++i)) { for (int j = 0; (j < static_cast(a[i].size())); (++j)) { (a[i][j] = v); } } } void ArrayUtils2D::fill(const vector>& a_const, int v) { auto& a = const_cast>&>(a_const); for (int i = 0; (i < static_cast(a.size())); (++i)) { ArrayUtils::fill(a[i], v); } } void MinimumCostFlow::addEdge(int from, int to, long long cost, long long cap) { shared_ptr e = make_shared(this, from, to, cost, cap); shared_ptr ie = make_shared(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 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& o_const) { shared_ptr 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> pq = JPriorityQueue>(); pq.add(make_shared(src, 0)); while ((!pq.empty())) { shared_ptr state = pq.poll(); if ((state->d_ > this->d[state->v_])) { continue; } for (shared_ptr 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(e->to, this->d[e->to])); (this->incommingShortestPathEdge[e->to] = e); } } for (shared_ptr 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(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]); } } } 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); } shared_ptr Main::eval(const vector& A_const, const vector>& S_const, const vector>>& memo_const) { auto& A = const_cast&>(A_const); auto& S = const_cast>&>(S_const); auto& memo = const_cast>>&>(memo_const); ArrayUtils::fill(memo, (-1)); int N = static_cast(S.size()); vector B = vector((4 * N)); vector di = vector{1, 0, (-1), 0}; vector dj = vector{0, (-1), 0, 1}; for (int t = 0; (t < static_cast(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); } } } } } } (memo[dir][i][j] = t); (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 make_shared(B, static_cast(Permutation::inversion(B))); } void Main::javaMain(const vector& args_const) { auto& args = const_cast&>(args_const); make_shared()->run(); MyPrintWriter::getInstance()->flush(); } void Main::run() { shared_ptr sc = FastScanner::getInstance(); shared_ptr pw = MyPrintWriter::getInstance(); int N = sc->nextInt(); vector A = sc->nextInts((4 * N)); long long startTime = System::nanoTime(); ArrayUtils::decrementAll(A); vector> S = vector>(N, vector(N)); ArrayUtils::fill(S, '0'); shared_ptr mf = make_shared(((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); vector>> memo = vector>>(4, vector>(N, vector(N))); auto initialResult = this->eval(A, S, memo); long long curScore = initialResult->score_; vector B = initialResult->B_; vector ts = vector(4); vector oldB = vector(4); double startTmp = 30; double endTmp = 1; double progress = 0; double curTmp = startTmp; for (int T = 0; (T < 1000000); (T++)) { if (((T & 127) == 0)) { long long dt = (System::nanoTime() - startTime); if ((dt >= TL)) { jeprintln(jconcat(JString("iteration"), T)); break; } (progress = ((1.0 * dt) / TL)); (curTmp = (startTmp * std::pow((endTmp / startTmp), progress))); } int i = this->rnd.nextInt(N); int j = this->rnd.nextInt(N); int v = this->rnd.nextInt(4); if ((v == 3)) { (v = 0); } if (((S[i][j] - '0') == v)) { continue; } char pre = S[i][j]; int k = 0; for (int d = 0; (d < 4); (d++)) { int t = memo[d][i][j]; if ((t == (-1))) { continue; } bool dup = false; for (int x = 0; (x < k); (x++)) { if ((ts[x] == t)) { (dup = true); } } if ((!dup)) { (ts[(k++)] = t); } } for (int x = 0; (x < k); (x++)) { (oldB[x] = B[ts[x]]); } for (int x = 0; (x < k); (x++)) { this->trace(S, memo, N, ts[x], (-1)); } (S[i][j] = static_cast(('0' + v))); for (int x = 0; (x < k); (x++)) { (B[this->trace(S, memo, N, ts[x], ts[x])] = A[ts[x]]); } long long score = Permutation::inversion(B); bool update = ((score > curScore) || (this->rnd.nextDouble() < std::exp(((score - curScore) / curTmp)))); if (update) { for (int x = 0; (x < k); (x++)) { this->trace(S, memo, N, ts[x], (-1)); } (S[i][j] = pre); for (int x = 0; (x < k); (x++)) { this->trace(S, memo, N, ts[x], ts[x]); } for (int x = 0; (x < k); (x++)) { (B[ts[x]] = oldB[x]); } } else { (curScore = score); } } pw->println(S); } int Main::trace(const vector>& S_const, const vector>>& memo_const, int N, int t, int mark) { auto& S = const_cast>&>(S_const); auto& memo = const_cast>>&>(memo_const); 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) { char c = S[i][j]; if ((c == '1')) { (dir ^= 1); } else { if ((c == '2')) { (dir = (3 - dir)); } } (memo[dir][i][j] = mark); (i += Main::DI[dir]); (j += Main::DJ[dir]); if ((i < 0)) { return j; } if ((i >= N)) { return (((3 * N) - 1) - j); } if ((j < 0)) { return (((4 * N) - 1) - i); } if ((j >= N)) { return (N + i); } } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << setprecision(16); Main::javaMain({}); return 0; }