結果
| 問題 | No.5026 Spectrum Router |
| コンテスト | |
| ユーザー |
37zigen
|
| 提出日時 | 2026-11-24 16:03:30 |
| 言語 | C++23 (gcc 15.3.0 + boost 1.92.0 + ACL) |
| 結果 |
TLE
不安定
|
| 実行時間 | - |
| コード長 | 100,767 bytes |
| 記録 | |
| コンパイル時間 | 5,738 ms |
| コンパイル使用メモリ | 413,632 KB |
| 実行使用メモリ | 6,400 KB |
| スコア | 0 |
| 最終ジャッジ日時 | 2026-11-24 16:03:57 |
| 合計ジャッジ時間 | 17,165 ms |
|
ジャッジサーバーID (参考情報) |
judge4_0 / judge6_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | TLE * 1 -- * 49 |
ソースコード
#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); }
};
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; }
};
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 FastScanner;
struct MyPrintWriter;
struct PopcountBIT;
struct Permutation;
struct ArrayUtils;
struct ArrayUtils2D;
struct MinimumCostFlow;
struct Main;
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 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>){};
};
struct PopcountBIT : public std::enable_shared_from_this<PopcountBIT> {
virtual ~PopcountBIT() = default;
PopcountBIT(const vector<bool>& 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<long long> bits = {};
vector<int> tree = {};
int total = {};
};
struct Permutation : public std::enable_shared_from_this<Permutation> {
virtual ~Permutation() = default;
Permutation();
static long long inversion(const vector<int>& a_const);
};
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 void fill(const vector<int>& a_const, int v);
static void fill(const vector<vector<int>>& a_const, int v);
static void fill(const vector<vector<vector<int>>>& a_const, int v);
static long long max(const vector<long long>& a_const);
};
struct ArrayUtils2D : public std::enable_shared_from_this<ArrayUtils2D> {
virtual ~ArrayUtils2D() = default;
ArrayUtils2D();
static void fill(const vector<vector<char>>& a_const, char v);
static void fill(const vector<vector<int>>& a_const, int v);
};
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 Main : public std::enable_shared_from_this<Main> {
struct Result;
struct Result : public std::enable_shared_from_this<Result> {
virtual ~Result() = default;
Result(const vector<int>& B_const, int score) {
vector<int> B = B_const;
(this->B_ = B);
(this->score_ = score);
}
template<class F0, class F1, class = enable_if_t<!is_same_v<decay_t<F0>, Result> && !(is_same_v<decay_t<F0>, vector<int>> && is_same_v<decay_t<F1>, int>)>> Result(F0&& p0, F1&& p1) {
jassign(this->B_, std::forward<F0>(p0));
jassign(this->score_, std::forward<F1>(p1));
}
virtual vector<int> B() {
return this->B_;
}
virtual int score() {
return this->score_;
}
vector<int> B_ = {};
int score_ = {};
};
virtual ~Main() = default;
Main();
virtual int cost(int i0, int v0, int i1, int v1);
virtual shared_ptr<struct Result> eval(const vector<int>& A_const, const vector<vector<char>>& S_const, const vector<vector<vector<int>>>& memo_const);
static void javaMain(const vector<JString>& args_const);
virtual void run();
virtual int trace(const vector<vector<char>>& S_const, const vector<vector<vector<int>>>& memo_const, int N, int t, int mark);
inline static JRandom rnd = JRandom(0);
inline static vector<int> DI = vector<int>{1, 0, (-1), 0};
inline static vector<int> DJ = vector<int>{0, (-1), 0, 1};
};
FastScanner::FastScanner() {
}
MyPrintWriter::MyPrintWriter() : JPrintWriter(JPrintWriter()) {
}
MyPrintWriter::MyPrintWriter(const JPrintWriter& out_const) : JPrintWriter(out_const) {
auto& out = const_cast<JPrintWriter&>(out_const);
}
PopcountBIT::PopcountBIT(const vector<bool>& a_const) : PopcountBIT(static_cast<int>(a_const.size())) {
auto& a = const_cast<vector<bool>&>(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<long long>(this->words));
(this->tree = vector<int>((this->words + 1)));
}
Permutation::Permutation() {
}
ArrayUtils::ArrayUtils() {
}
ArrayUtils2D::ArrayUtils2D() {
}
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>>());
}
}
Main::Main() {
}
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);
}
}
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]);
}
}
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<int>& a_const) {
auto& a = const_cast<vector<int>&>(a_const);
int n = static_cast<int>(a.size());
shared_ptr<struct PopcountBIT> tree = make_shared<struct PopcountBIT>(n);
long long ans = 0;
for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
(ans += (i - tree->sum(a[i])));
tree->set(a[i], true);
}
return ans;
}
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);
}
void ArrayUtils::fill(const vector<int>& a_const, int v) {
auto& a = const_cast<vector<int>&>(a_const);
jfill(a, v);
}
void ArrayUtils::fill(const vector<vector<int>>& a_const, int v) {
auto& a = const_cast<vector<vector<int>>&>(a_const);
ArrayUtils2D::fill(a, v);
}
void ArrayUtils::fill(const vector<vector<vector<int>>>& a_const, int v) {
auto& a = const_cast<vector<vector<vector<int>>>&>(a_const);
for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
ArrayUtils::fill(a[i], 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;
}
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);
}
}
}
void ArrayUtils2D::fill(const vector<vector<int>>& a_const, int v) {
auto& a = const_cast<vector<vector<int>>&>(a_const);
for (int i = 0; (i < static_cast<int>(a.size())); (++i)) {
ArrayUtils::fill(a[i], v);
}
}
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]);
}
}
}
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::Result> Main::eval(const vector<int>& A_const, const vector<vector<char>>& S_const, const vector<vector<vector<int>>>& memo_const) {
auto& A = const_cast<vector<int>&>(A_const);
auto& S = const_cast<vector<vector<char>>&>(S_const);
auto& memo = const_cast<vector<vector<vector<int>>>&>(memo_const);
ArrayUtils::fill(memo, (-1));
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);
}
}
}
}
}
}
(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<struct Result>(B, static_cast<int>(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) * 10000);
vector<vector<vector<int>>> memo = vector<vector<vector<int>>>(4, vector<vector<int>>(N, vector<int>(N)));
auto initialResult = this->eval(A, S, memo);
long long curScore = initialResult->score_;
vector<int> B = initialResult->B_;
vector<int> ts = vector<int>(4);
vector<int> oldB = vector<int>(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<char>(('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<vector<char>>& S_const, const vector<vector<vector<int>>>& memo_const, int N, int t, int mark) {
auto& S = const_cast<vector<vector<char>>&>(S_const);
auto& memo = const_cast<vector<vector<vector<int>>>&>(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;
}
37zigen