#pragma GCC optimize("O3,unroll-loops") #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using lint = long long; using pint = pair; using plint = pair; struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_; #define ALL(x) (x).begin(), (x).end() #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i=i##_begin_;i--) #define REP(i, n) FOR(i,0,n) #define IREP(i, n) IFOR(i,0,n) template bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; } template bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; } int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); } template T1 floor_div(T1 num, T2 den) { return (num > 0 ? num / den : -((-num + den - 1) / den)); } template std::pair operator+(const std::pair &l, const std::pair &r) { return std::make_pair(l.first + r.first, l.second + r.second); } template std::pair operator-(const std::pair &l, const std::pair &r) { return std::make_pair(l.first - r.first, l.second - r.second); } template std::vector sort_unique(std::vector vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; } template int arglb(const std::vector &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); } template int argub(const std::vector &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); } template IStream &operator>>(IStream &is, std::vector &vec) { for (auto &v : vec) is >> v; return is; } template OStream &operator<<(OStream &os, const std::vector &vec); template OStream &operator<<(OStream &os, const std::array &arr); template OStream &operator<<(OStream &os, const std::unordered_set &vec); template OStream &operator<<(OStream &os, const pair &pa); template OStream &operator<<(OStream &os, const std::deque &vec); template OStream &operator<<(OStream &os, const std::set &vec); template OStream &operator<<(OStream &os, const std::multiset &vec); template OStream &operator<<(OStream &os, const std::unordered_multiset &vec); template OStream &operator<<(OStream &os, const std::pair &pa); template OStream &operator<<(OStream &os, const std::map &mp); template OStream &operator<<(OStream &os, const std::unordered_map &mp); template OStream &operator<<(OStream &os, const std::tuple &tpl); template OStream &operator<<(OStream &os, const std::vector &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; } template OStream &operator<<(OStream &os, const std::array &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; } template std::istream &operator>>(std::istream &is, std::tuple &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; } template OStream &operator<<(OStream &os, const std::tuple &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; } template OStream &operator<<(OStream &os, const std::unordered_set &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template OStream &operator<<(OStream &os, const std::deque &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; } template OStream &operator<<(OStream &os, const std::set &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template OStream &operator<<(OStream &os, const std::multiset &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template OStream &operator<<(OStream &os, const std::unordered_multiset &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; } template OStream &operator<<(OStream &os, const std::pair &pa) { return os << '(' << pa.first << ',' << pa.second << ')'; } template OStream &operator<<(OStream &os, const std::map &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; } template OStream &operator<<(OStream &os, const std::unordered_map &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; } #ifdef HITONANODE_LOCAL const string COLOR_RESET = "\033[0m", BRIGHT_CYAN = "\033[1;36m"; #define dbgif(cond, x) ((cond) ? std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << " (L" << __LINE__ << ") " << __FILE__ << std::endl : std::cerr) #define dbg(x) dbgif(true, x) #else #define dbg(x) ((void)0) #define dbgif(cond, x) ((void)0) #endif // https://hitonanode.github.io/cplib-cpp/heuristic/exponential_dist_sampler.hpp #include #include #include #include template struct ExponentialDistSampler { std::array minuslogps; constexpr ExponentialDistSampler() { for (int i = 0; i < (1 << D); ++i) minuslogps.at(i) = -log((0.5 + i) / (1 << D)); } double sample(uint32_t random_mask) const { return minuslogps.at(random_mask & ((1 << D) - 1)); } // p ~ U(0, 1) => -log(p) ~ Ex(1) // P[exp(-|dx| / T) >= p] = P[|dx| <= -log(p) * T] bool check_sa(double abs_dx, double T, uint32_t random_mask) const { return abs_dx <= minuslogps.at(random_mask & ((1 << D) - 1)) * T; } }; const ExponentialDistSampler<16> log_ps; template struct Annealer { static_assert(UPDATE_INTERVAL > 0); double temp; double ratio; int next_update = UPDATE_INTERVAL; Annealer(double start_temp, double end_temp, int iterations) : temp(start_temp) { assert(iterations > 0); const int updates = (iterations - 1) / UPDATE_INTERVAL; ratio = updates == 0 ? 1.0 : pow(end_temp / start_temp, 1.0 / updates); // ratio = updates == 0 ? 0.0 : (end_temp - start_temp) / updates; } void update(int iter) { if (iter >= next_update) { temp *= ratio; // temp += ratio; next_update += UPDATE_INTERVAL; } } template bool accept_score(int delta_score, RNG &rng, const Sampler &sampler) const { if (delta_score >= 0) return true; return sampler.check_sa(-delta_score, temp, rng.next_u16()); } template bool accept_cost(int delta_cost, RNG &rng, const Sampler &sampler) const { if (delta_cost <= 0) return true; return sampler.check_sa(delta_cost, temp, rng.next_u16()); } }; // https://hitonanode.github.io/cplib-cpp/random/rand_nondeterministic.hpp #include #include #include #include struct RNGMt19937 { using lint = long long; std::mt19937 mt; RNGMt19937(long long seed) : mt(seed) {} lint operator()(lint x) { // [0, x) assert(x > 0); return this->operator()(0, x); } lint operator()(lint l, lint r) { assert(l < r); std::uniform_int_distribution d(l, r - 1); return d(mt); } }; // RNGMt19937 rnd(123456789); // RNGMt19937 rnd(std::chrono::steady_clock::now().time_since_epoch().count()); // Fast random number generator based on xoshiro256++. struct FastRNG { using ull = unsigned long long; ull s[4]; static ull rotl(ull x, int k) { return (x << k) | (x >> (64 - k)); } static ull splitmix64(ull &x) { ull z = (x += 0x9e3779b97f4a7c15ULL); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; return z ^ (z >> 31); } FastRNG(ull seed) { for (auto &x : s) x = splitmix64(seed); } ull next_u64() { ull res = rotl(s[0] + s[3], 23) + s[0]; ull t = s[1] << 17; s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = rotl(s[3], 45); return res; } uint32_t next_u32() { return next_u64() >> 32; } // [0, n) uint32_t operator()(uint32_t n) { assert(n > 0); return (uint64_t(next_u32()) * n) >> 32; } // [l, r) int operator()(int l, int r) { assert(l < r); uint32_t width = uint64_t(int64_t(r) - int64_t(l)); return int(int64_t(l) + (*this)(width)); } uint16_t next_u16() { return next_u64() >> 48; } }; inline FastRNG rnd(123456789); // FastRNG rnd(std::chrono::steady_clock::now().time_since_epoch().count()); // https://hitonanode.github.io/cplib-cpp/segmenttree/binary_indexed_tree.hpp #include #include // 0-indexed BIT (binary indexed tree / Fenwick tree) (i : [0, len)) template struct BIT { int n; std::vector data; BIT(int len = 0) : n(len), data(len) {} void reset() { std::fill(data.begin(), data.end(), T(0)); } void add(int pos, T v) { // a[pos] += v pos++; while (pos > 0 and pos <= n) data[pos - 1] += v, pos += pos & -pos; } T sum(int k) const { // a[0] + ... + a[k - 1] T res = 0; while (k > 0) res += data[k - 1], k -= k & -k; return res; } T sum(int l, int r) const { return sum(r) - sum(l); } // a[l] + ... + a[r - 1] template friend OStream &operator<<(OStream &os, const BIT &bit) { T prv = 0; os << '['; for (int i = 1; i <= bit.n; i++) { T now = bit.sum(i); os << now - prv << ',', prv = now; } return os << ']'; } }; constexpr int N = 64; constexpr int M = 64 * 4; array A; using State = array; using Mates = array; State init() { State s; s.fill(0); return s; } // UDLR const std::vector> grid_dxs{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; const int UP = 0, DOWN = 1, RIGHT = 2, LEFT = 3; struct PosDir { int x = -1; int y = -1; int dir = -1; bool isin() const { return 0 <= x && x < N && 0 <= y && y < N; } int f() const { return x * N + y; } PosDir step() const { auto ret = *this; ret.x += grid_dxs.at(dir).first; ret.y += grid_dxs.at(dir).second; return ret; } int IO_ID() const { assert(!isin()); assert((0 <= x and x < N) or (0 <= y and y < N)); if (x == -1) return y; if (y == N) return N + x; if (x == N) return 3 * N - 1 - y; if (y == -1) return 4 * N - 1 - x; assert(false); } template friend OStream &operator<<(OStream &os, const PosDir &pos) { return os << '(' << pos.x << ',' << pos.y << ',' << pos.dir << ')'; } }; PosDir InitialPos(int i) { assert(0 <= i); assert(i < N * 4); if (i < N) return {0, i, DOWN}; if (i < N * 2) return {i - N, N - 1, LEFT}; if (i < N * 3) return {N - 1, N * 3 - 1 - i, UP}; if (i < N * 4) return {N * 4 - 1 - i, 0, RIGHT}; assert(false); } PosDir Move(const State &s, PosDir cur) { const int m = s.at(cur.f()); if (m == 0) { } else if (m == 1) { static const vector trans{RIGHT, LEFT, UP, DOWN}; cur.dir = trans.at(cur.dir); } else if (m == 2) { static const vector trans{LEFT, RIGHT, DOWN, UP}; cur.dir = trans.at(cur.dir); } else { assert(false); } return cur.step(); } Mates CalculatePairs(const State &s) { Mates mates; mates.fill(-1); for (int i = 0; i < N * 4; ++i) { if (mates.at(i) != -1) continue; auto pos = InitialPos(i); while (pos.isin()) { pos = Move(s, pos); } const int j = pos.IO_ID(); if (i == j) { dbg(i); dbg(j); dbg(pos); } assert(i != j); assert(mates.at(j) == -1); mates.at(i) = j; mates.at(j) = i; } return mates; } int Score(const Mates &mates) { Mates seq; REP(i, M) seq.at(i) = A.at(mates.at(i)); BIT bit(M); int score = M * (M - 1) / 2; REP(i, M) { score -= bit.sum(seq.at(i), M); bit.add(seq.at(i), 1); } return score; } int f(int x, int y) { assert(0 <= x and x < N); assert(0 <= y and y < N); return x * N + y; } int main() { { int N_; cin >> N_; assert(N == N_); for (auto &a : A) { int t; cin >> t; --t; a = t; } } dbg(A); auto state = init(); const auto mates = CalculatePairs(state); int score = Score(mates); int best_score = score; auto best_state = state; constexpr int ITERATIONS = 70000; Annealer<> annealer(1, 1, ITERATIONS); REP(_, ITERATIONS) { annealer.update(_); int x = rnd(N), y = rnd(N); int d = rnd(1, 3); int old = state.at(f(x, y)); state.at(f(x, y)) = (state.at(f(x, y)) + d) % 3; const auto new_score = Score(CalculatePairs(state)); if (annealer.accept_score(new_score - score, rnd, log_ps)) { score = new_score; if (score > best_score) { best_score = score; best_state = state; } } else { state.at(f(x, y)) = old; } } dbg(best_score); REP(x, N) { REP(y, N) cout << best_state.at(f(x, y)); cout << '\n'; } }