// ---------------- ここからテンプレ、修正しないこと ----------------- //* #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") //*/ #include // #include using namespace std; // using namespace atcoder; // #define _GLIBCXX_DEBUG #ifdef LOCAL #define DEBUG(x) cerr << #x << ": " << x << endl; #define DEBUG_VEC(v) \ cerr << #v << ":"; \ for (int iiiiiiii = 0; iiiiiiii < v.size(); iiiiiiii++) \ cerr << " " << v[iiiiiiii]; \ cerr << endl; #define DEBUG_MAT(v) \ cerr << #v << endl; \ for (int iv = 0; iv < v.size(); iv++) { \ for (int jv = 0; jv < v[iv].size(); jv++) { \ cerr << v[iv][jv] << " "; \ } \ cerr << endl; \ } #else #define DEBUG(x) ; #define DEBUG_VEC(v) ; #define DEBUG_MAT(v) ; #endif typedef long long ll; // #define int ll #define vi vector #define vl vector #define vii vector> #define vll vector> #define pii pair #define pis pair #define psi pair #define pll pair template pair operator+(const pair &s, const pair &t) { return pair(s.first + t.first, s.second + t.second); } template pair operator-(const pair &s, const pair &t) { return pair(s.first - t.first, s.second - t.second); } template ostream &operator<<(ostream &os, pair p) { os << "(" << p.first << ", " << p.second << ")"; return os; } #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define rep1(i, n) for (int i = 1; i <= (int)(n); i++) #define rrep(i, n) for (int i = (int)(n) - 1; i >= 0; i--) #define rrep1(i, n) for (int i = (int)(n); i > 0; i--) #define REP(i, a, b) for (int i = a; i < b; i++) #define in(x, a, b) (a <= x && x < b) #define all(c) c.begin(), c.end() void YES(bool t = true) { cout << (t ? "YES" : "NO") << endl; } void Yes(bool t = true) { cout << (t ? "Yes" : "No") << endl; } void yes(bool t = true) { cout << (t ? "yes" : "no") << endl; } void NO(bool t = true) { cout << (t ? "NO" : "YES") << endl; } void No(bool t = true) { cout << (t ? "No" : "Yes") << endl; } void no(bool t = true) { cout << (t ? "no" : "yes") << endl; } template bool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } template bool chmin(T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; } template T ceil_div(T a, U b) { return (a + b - 1) / b; } template T safe_mul(T a, T b) { if (a == 0 || b == 0) return 0; if (numeric_limits::max() / a < b) return numeric_limits::max(); return a * b; } #define UNIQUE(v) v.erase(std::unique(v.begin(), v.end()), v.end()); const ll inf = 1000000001; const ll INF = (ll)1e18 + 1; const long double pi = 3.1415926535897932384626433832795028841971L; int popcount(ll t) { return __builtin_popcountll(t); } vector gen_perm(int n) { vector ret(n); iota(all(ret), 0); return ret; } // int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; // int dx2[8] = { 1,1,0,-1,-1,-1,0,1 }, dy2[8] = { 0,1,1,1,0,-1,-1,-1 }; vi dx = {0, 1, 0, -1}, dy = {-1, 0, 1, 0}; vi dx2 = {1, 1, 0, -1, -1, -1, 0, 1}, dy2 = {0, 1, 1, 1, 0, -1, -1, -1}; struct Setup_io { Setup_io() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); cout << fixed << setprecision(25); cerr << fixed << setprecision(25); } } setup_io; // constexpr ll MOD = 1000000007; constexpr ll MOD = 998244353; // #define mp make_pair auto start = chrono::system_clock::now(); constexpr double TL = 1.95; double calc_seconds() { return static_cast(chrono::duration_cast( chrono::system_clock::now() - start) .count() / 1000000.0); } #ifdef LOCAL struct TimerRegistry { struct Entry { double total = 0.0; int count = 0; }; unordered_map data; static TimerRegistry &instance() { static TimerRegistry reg; return reg; } void add(const string &name, double elapsed) { data[name].total += elapsed; data[name].count++; } void print() const { vector> v(data.begin(), data.end()); sort(v.begin(), v.end(), [](auto &a, auto &b) { return a.second.total > b.second.total; }); cerr << "=== Timer Report ===" << endl; for (auto &[name, e] : v) { cerr << name << ": total=" << e.total << "s" << " count=" << e.count << " avg=" << e.total / e.count << "s" << endl; } } ~TimerRegistry() { print(); } }; struct ScopedTimer { string name; chrono::time_point t0; ScopedTimer(const string &n) : name(n), t0(chrono::system_clock::now()) {} ~ScopedTimer() { double elapsed = chrono::duration(chrono::system_clock::now() - t0).count(); TimerRegistry::instance().add(name, elapsed); } }; #define TIMER(name) ScopedTimer _st_##name(#name) #define PRINT_TIMERS() TimerRegistry::instance().print() #else #define TIMER(name) #define PRINT_TIMERS() #endif class HRandom { public: HRandom() { random_mw = 1985; random_mz = 2012; } int intRandom() { random_mz = 36969 * (random_mz & 65535) + (random_mz >> 16); random_mw = 18000 * (random_mw & 65535) + (random_mw >> 16); unsigned result = (random_mz << 16) + random_mw; return result >> 1; } unsigned int uintRandom_65535() { // random_mz = 36969 * (random_mz & 65535) + (random_mz >> 16); // random_mw = 18000 * (random_mw & 65535) + (random_mw >> 16); // return random_mw & 65535; const unsigned tmp = random_mw & 65535; random_mw = 18000 * tmp + (random_mw >> 16); return tmp; } unsigned int uintRandom() { random_mz = 36969 * (random_mz & 65535) + (random_mz >> 16); random_mw = 18000 * (random_mw & 65535) + (random_mw >> 16); unsigned result = (random_mz << 16) + random_mw; return result; } double dblRandom() { random_mz = 36969 * (random_mz & 65535) + (random_mz >> 16); random_mw = 18000 * (random_mw & 65535) + (random_mw >> 16); unsigned result = (random_mz << 16) + random_mw; return (result + 1.0) * 2.328306435454494e-10; } private: unsigned random_mw; unsigned random_mz; }; HRandom hrandom; static uint32_t randxor() { static uint32_t x = 123456789; static uint32_t y = 362436069; static uint32_t z = 521288629; static uint32_t w = 88675123; uint32_t t; t = x ^ (x << 11); x = y; y = z; z = w; return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); } void randxor_init() {} double randdouble() { return hrandom.dblRandom(); } bool randbool(const float &p = 0.5) { return hrandom.uintRandom_65535() < (p * 65535); } inline int rnd(const int n) { assert(0 <= n); if (n == 1) { return 0; } return ((hrandom.uintRandom_65535()) * n) >> 16; } int rnd(const int &l, const int &r) { assert(l <= r); return rnd(r - l) + l; } struct GaussianSampler { vector buf; size_t idx = 0; GaussianSampler(size_t table_size = 1 << 10) { init(table_size); } void init(size_t table_size) { if (table_size % 2 == 1) table_size++; // 2個ずつ埋めるので偶数に buf.resize(table_size); idx = 0; const double two_pi = 2.0 * (double)pi; for (size_t i = 0; i < table_size; i += 2) { // Box-Muller で2個ずつ生成(初期化時のみコストを払う) double u1 = max(1e-12, randdouble()); double u2 = randdouble(); double r = sqrt(-2.0 * log(u1)); double th = two_pi * u2; double z0 = r * cos(th); double z1 = r * sin(th); buf[i] = z0; buf[i + 1] = z1; } } inline double sample(double mu = 0.0, double sigma = 1.0) { if (idx >= buf.size()) idx = 0; // wrap return mu + sigma * buf[idx++]; } }; GaussianSampler gaussian_sampler; class Parameter { public: Parameter() {} static Parameter from_env() { return Parameter(); // return Parameter(getenv("START_TEMP") ? stof(getenv("START_TEMP")) // : START_TEMP); } }; Parameter param; std::default_random_engine engine(42); // ---------------- ここまでテンプレ、修正しないこと ----------------- constexpr int N = 64, M = 256; array A; array laser2port; void input() { int dummy; cin >> dummy; rep(i, M) { cin >> A[i]; A[i]--; laser2port[A[i]] = i; } } struct AnnealingState { using Cost = int; Cost score; Cost best_score; double start_sec, end_sec; double temperature; array, N> state; array, N> best_state; // [y, x] に d から入ってくる光がどのポートからか array, N>, N> from_port; // [y, x] の d から出ていく行き先のポート array, N>, N> to_port; array B; AnnealingState(double end_sec) : start_sec(calc_seconds()), end_sec(end_sec) { init(); } void init() { build_initial(); // TODO: 最小化か最大化かで、best_scoreの初期値を変える // この例は最小化の場合 best_score = inf; update_best(); } void build_initial() { rep(i, M) { update_from_port(i); } score = calc_score(); } void update_from_port(int port_idx, bool reset = false) { int y, x, d; if (port_idx < N) { y = 0, x = port_idx, d = 0; } else if (port_idx < 2 * N) { y = port_idx - N, x = N - 1, d = 1; } else if (port_idx < 3 * N) { y = N - 1, x = 3 * N - 1 - port_idx, d = 2; } else { y = 4 * N - 1 - port_idx, x = 0, d = 3; } vector> yxd; while (in(y, 0, N) && in(x, 0, N)) { if (!reset) { from_port[y][x][d] = port_idx; } else { from_port[y][x][d] = -1; } d = change_dir(d, state[y][x]); yxd.emplace_back(y, x, (d + 2) % 4); y += dy[(d + 2) % 4]; x += dx[(d + 2) % 4]; } int to_port_idx = get_port_idx(y, x); if (!reset) { B[to_port_idx] = A[port_idx]; } else { B[to_port_idx] = -1; } for (auto [y, x, d] : yxd) { if (!reset) { to_port[y][x][d] = to_port_idx; } else { to_port[y][x][d] = -1; } } } int calc_score() { int ans = 0; rep(i, M) { int x = B[i]; rep(j, i) { if (B[j] > x) { ans++; } } } return ans; } // pos のいずれかを含むペアの転倒数 O(4M) int calc_partial_inversion(const array &pos) const { int res = 0; rep(k, 4) { int i = pos[k], v = B[i]; int c = 0; for (int j = 0; j < i; j++) { c += B[j] > v; } for (int j = i + 1; j < M; j++) { c += B[j] < v; } res += c; } // pos 同士のペアは 2 回数えているので 1 回分引く rep(k, 4) rep(l, k) { int i = pos[l], j = pos[k]; if (i > j) { swap(i, j); } res -= B[i] > B[j]; } return res; } int get_port_idx(int y, int x) { if (y == -1) { return x; } if (x == N) { return y + N; } if (y == N) { return 3 * N - 1 - x; } if (x == -1) { return 4 * N - 1 - y; } assert(false); } // d から入ってきたやつは、次のやつのどれに入るか int change_dir(int d, int s) { if (s == 0) { return d; } if (s == 1) { switch (d) { case 0: return 1; case 1: return 0; case 2: return 3; default: return 2; } } if (s == 2) { switch (d) { case 0: return 3; case 1: return 2; case 2: return 1; default: return 0; } } assert(false); } void solve() { // TODO: 温度の設定を変える double start_temp = 5.0, end_temp = 1.0; rep(try_num, inf) { if (try_num % 16 == 0) { double sec = calc_seconds(); if (should_stop(try_num, sec)) { DEBUG(try_num); break; } double rate = decide_rate(try_num, sec); set_temperature(rate, start_temp, end_temp); } step(); } } inline bool should_stop(int try_num, double sec) const { #ifdef FREEZE return try_num > 10000000; #else return sec > end_sec; #endif } double decide_rate(int try_num, double sec) const { #ifdef FREEZE // フリーズしている場合は、10000回に1回の確率で温度を下げる return try_num / 10000000.0; #else return (sec - start_sec) / (end_sec - start_sec); #endif } void set_temperature(double rate, double start_temp, double end_temp) { // temperature = start_temp + (end_temp - start_temp) * rate; temperature = start_temp * pow(end_temp / start_temp, rate); } void step() { int y = rnd(N), x = rnd(N); int s_seed = rnd(5); int s = max(0, s_seed - 2); if (state[y][x] == s) { return; } int ori_s = state[y][x]; // (入ってくるポート, 今の出口ポート) と、変更後の出口ポート array in_from, ori_to, new_to; int cnt = 0; rep(d, 4) { int p = from_port[y][x][d]; if (p == -1) { continue; } in_from[cnt] = p; // change_dir の戻り値 +2 が、このマスから出ていく辺 ori_to[cnt] = to_port[y][x][(change_dir(d, ori_s) + 2) % 4]; new_to[cnt] = to_port[y][x][(change_dir(d, s) + 2) % 4]; cnt++; } bool distinct = cnt == 4; rep(i, cnt) rep(j, i) { if (in_from[i] == in_from[j]) { distinct = false; } } if (!distinct) { // 4 辺が 4 つの異なるポートに直結していないケース: // - 同じ経路がこのマスを 2 回通る (外側で辺 b-c がつながっている) // - 片方の通路がループ上 (from_port == -1) // - 両方の通路がループ上 // いずれも外側で「ポートにつながる辺」は高々 2 つで、 // 残りの 2 辺は外側で互いにつながっている。 // どう繋ぎ変えても、ポートにつながる 2 辺は (ループを経由するか // 直接かの違いだけで) 互いにつながるので、出口の対応は不変。 // => スコア変化 0 // で、経路の形だけ変わる中立な遷移として常に鏡を外す。 apply_change(y, x, 0, in_from, cnt); return; } // 値が入れ替わるのは in_from の 4 ポート (= 出口の集合も同じ 4 ポート) // だけなので、それらが関わる転倒だけを数え直す int before = calc_partial_inversion(in_from); rep(i, 4) { B[new_to[i]] = A[in_from[i]]; } int after = calc_partial_inversion(in_from); Cost new_score = score + after - before; Cost score_diff = new_score - score; if (should_accept(score_diff)) { apply_change(y, x, s, in_from, cnt); score = new_score; update_best(); return; } rep(i, 4) { B[ori_to[i]] = A[in_from[i]]; } } // (y, x) を s に変更し、そこを通る経路を引き直す void apply_change(int y, int x, int s, const array &ports, int cnt) { rep(i, cnt) { update_from_port(ports[i], true); } state[y][x] = s; // 新しい経路は、旧経路のほかにループだった部分を取り込むことがあるが、 // ポートから引き直せば全部書き込まれる rep(i, cnt) { update_from_port(ports[i]); } } bool should_accept(Cost score_diff) const { // TODO: 最小化か最大化かで、expの中の符号を変える // この例は最小化の場合 if (score_diff <= 0) { return true; } return randdouble() < exp(-score_diff / temperature); } bool update_best() { // TODO: 最小化か最大化かで、best_scoreの比較を変える if (score < best_score) { best_score = score; best_state = state; DEBUG(best_score); return true; } return false; } }; signed main(int argc, char **argv) { input(); AnnealingState anneal(TL); anneal.solve(); DEBUG(anneal.best_score); rep(i, N) { rep(j, N) { cout << anneal.best_state[i][j]; } cout << endl; } }