#include using namespace std; using namespace chrono; #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") using Graph = vector>; #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(), v.rend() constexpr long long INF = (1LL << 60); #define gcd(a, b) __gcd((a), (b)) #define ll long long #define fi first #define se second #define mod107 1000000007 #define mod998 998244353 #define eps 1e-9 #define PI acos(-1) #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define SHOW(x) std::clog << #x ": " << (x) << std::endl bool DEBUG = false; template bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } struct HyperParameterConfig { }; const HyperParameterConfig &hyper_params() { static HyperParameterConfig cfg = []() { HyperParameterConfig tmp; return tmp; }(); return cfg; } template istream &operator>>(istream &s, vector &v) { for (auto &e : v) s >> e; return s; } template ostream &operator<<(ostream &s, const vector &v) { for (auto &e : v) s << e << ' '; return s; } template ostream &operator<<(ostream &s, const pair &p) { s << p.first << ' ' << p.second; return s; } chrono::system_clock::time_point start_time; void start_timer() { start_time = chrono::system_clock::now(); } double get_time_global() { auto end_time = chrono::system_clock::now(); return chrono::duration_cast(end_time - start_time).count(); } template std::string debug_format(const T &value); template std::string debug_format(const std::pair &value) { return "(" + debug_format(value.first) + ", " + debug_format(value.second) + ")"; } template std::string debug_format(const std::vector &value) { std::string result = "["; for (size_t i = 0; i < value.size(); i++) { if (i > 0) result += ", "; result += debug_format(value[i]); } return result + "]"; } template std::string debug_format(const T &value) { std::ostringstream stream; stream << value; return stream.str(); } template void debug_impl(const char *names, const T &...values) { std::cerr << '[' << names << "] = "; size_t index = 0; ((std::cerr << (index++ == 0 ? "" : ", ") << debug_format(values)), ...); std::cerr << '\n'; } #ifdef LOCAL #define dbg(...) debug_impl(#__VA_ARGS__, __VA_ARGS__) #else #define dbg(...) ((void)0) #endif // AHCプロファイラ namespace ahc { using Clock = std::chrono::steady_clock; struct SearchStats { uint64_t trials = 0, accepted = 0; uint64_t improved = 0, best_updates = 0; long double initial_score = 0, best_score = 0; bool initialized = false, maximize = true; Clock::time_point started = Clock::now(); void init(long double score, bool is_maximize = true) { trials = accepted = improved = best_updates = 0; initial_score = best_score = score; maximize = is_maximize; initialized = true; started = Clock::now(); } void update_best(long double score) { if (!initialized) { init(score); return; } if ((maximize && score > best_score) || (!maximize && score < best_score)) { best_score = score; ++best_updates; } } }; inline SearchStats stats; // プロファイラ struct Profile { const char *name; uint64_t every, samples = 0; double measured_ms = 0; Profile(const char *name, uint64_t every); }; inline std::vector &profiles() { static std::vector items; return items; } inline Profile::Profile(const char *n, uint64_t k) : name(n), every(std::max(1, k)) { profiles().push_back(this); } // 任意のカウンタ struct Counter { const char *name; uint64_t value = 0; explicit Counter(const char *n); }; inline std::vector &counters() { static std::vector items; return items; } inline Counter::Counter(const char *n) : name(n) { counters().push_back(this); } // スコープを抜けると自動計測 struct ScopedTimer { Profile &p; bool enabled; Clock::time_point started; ScopedTimer(Profile &p, bool enabled) : p(p), enabled(enabled) { if (enabled) started = Clock::now(); } ~ScopedTimer() { if (!enabled) return; p.measured_ms += std::chrono::duration( Clock::now() - started) .count(); ++p.samples; } }; // 結果出力 inline void report() { using namespace std; double elapsed = chrono::duration( Clock::now() - stats.started) .count(); auto pct = [](uint64_t x, uint64_t n) { return n ? 100.0 * x / n : 0.0; }; cerr << fixed << setprecision(2); cerr << "\n========== AHC Statistics ==========\n"; cerr << "Elapsed : " << elapsed << " ms\n"; cerr << "Iterations : " << stats.trials << "\n"; cerr << "Iterations/s : " << (elapsed > 0 ? stats.trials * 1000.0 / elapsed : 0.0) << "\n"; cerr << "Accepted : " << stats.accepted << " (" << pct(stats.accepted, stats.trials) << "%)\n"; cerr << "Improvements : " << stats.improved << "\n"; cerr << "Best Updates : " << stats.best_updates << "\n"; if (stats.initialized) { cerr << "Initial Score: " << stats.initial_score << "\n"; cerr << "Best Score : " << stats.best_score << "\n"; } if (!counters().empty()) { map totals; for (auto *c : counters()) totals[c->name] += c->value; cerr << "\n---------- Custom Counters ----------\n"; for (auto &[name, value] : totals) cerr << name << ": " << value << "\n"; } cerr << "\n--------------- Profile -------------\n"; cerr << "Name Est.ms Avg.us Samples\n"; auto pp = profiles(); sort(pp.begin(), pp.end(), [](auto *a, auto *b) { return a->measured_ms * a->every > b->measured_ms * b->every; }); for (auto *p : pp) { if (!p->samples) continue; cerr << setw(18) << left << p->name << right << setw(11) << p->measured_ms * p->every << setw(11) << p->measured_ms * 1000 / p->samples << setw(10) << p->samples << "\n"; } cerr << "====================================\n"; } } // namespace ahc // マクロ #define AHC_CAT_(a, b) a##b #define AHC_CAT(a, b) AHC_CAT_(a, b) #ifdef LOCAL #define AHC_INIT(...) (::ahc::stats.init(__VA_ARGS__)) #define AHC_TRY() (++::ahc::stats.trials) #define AHC_ACCEPT() (++::ahc::stats.accepted) #define AHC_IMPROVE() (++::ahc::stats.improved) #define AHC_BEST(score) (::ahc::stats.update_best(score)) #define AHC_REPORT() (::ahc::report()) #define AHC_COUNT(name) AHC_COUNT_IMPL(name, __COUNTER__) #define AHC_COUNT_IMPL(name, id) \ do \ { \ static ::ahc::Counter AHC_CAT(_ahc_c_, id)(name); \ ++AHC_CAT(_ahc_c_, id).value; \ } while (0) #define AHC_PROFILE(name) \ AHC_PROFILE_IMPL(name, 1, __COUNTER__) #define AHC_PROFILE_SAMPLE(name, period) \ AHC_PROFILE_IMPL(name, period, __COUNTER__) #define AHC_PROFILE_IMPL(name, period, id) \ static ::ahc::Profile AHC_CAT(_ahc_p_, id)(name, period); \ static uint64_t AHC_CAT(_ahc_i_, id) = 0; \ ::ahc::ScopedTimer AHC_CAT(_ahc_t_, id)( \ AHC_CAT(_ahc_p_, id), \ (++AHC_CAT(_ahc_i_, id) % AHC_CAT(_ahc_p_, id).every) == 0) #else #define AHC_INIT(...) ((void)0) #define AHC_TRY() ((void)0) #define AHC_ACCEPT() ((void)0) #define AHC_IMPROVE() ((void)0) #define AHC_BEST(score) ((void)0) #define AHC_REPORT() ((void)0) #define AHC_COUNT(name) ((void)0) #define AHC_PROFILE(name) ((void)0) #define AHC_PROFILE_SAMPLE(name, period) ((void)0) #endif constexpr int di[8] = {-1, 0, 1, 0, 1, -1, -1, 1}; constexpr int dj[8] = {0, 1, 0, -1, 1, -1, 1, -1}; /// 乱数 /// ======== // 0以上UINT_MAX(0xffffffff)以下の整数をとる乱数 xorshift https://ja.wikipedia.org/wiki/Xorshift 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)); } inline double rand01() { return (randXor() + 0.5) * (1.0 / 4294967296.0); } // [l, r) inline int rand_int(int l, int r) { return l + randXor() % (r - l); } // 確率pでtrue inline bool rand_bool(double p) { return rand01() < p; } // vectorからランダム選択 template T &random_choice(vector &v) { return v[rand_int(0, (int)v.size())]; } // https://qandori.github.io/cp-library/sequence/inversion_count.hpp.html #line 1 "sequence/inversion_count.hpp" #line 1 "components/radix_sort.hpp" #include #include #include #include #include #include #include template void stable_radix_sort(std::vector &values, Key &&key) { static_assert(1 <= Bits && Bits <= 16); constexpr unsigned buckets = 1U << Bits, mask = buckets - 1; using K = std::remove_cvref_t()))>; static_assert(std::is_integral_v && std::is_unsigned_v && sizeof(K) <= sizeof(std::uint64_t)); if (values.size() < 2) return; if (values.size() < 256) { std::stable_sort(values.begin(), values.end(), [&](const T &a, const T &b) { return key(a) < key(b); }); return; } std::uint64_t first = key(values.front()), previous = first, varying = 0; bool sorted = true; for (std::size_t i = 1; i < values.size(); ++i) { std::uint64_t current = key(values[i]); varying |= first ^ current; sorted &= previous <= current; previous = current; } if (sorted) return; std::vector scratch(values.size()); if constexpr (Bits == 11 && sizeof(K) <= 4) { if (values.size() <= UINT32_MAX && (varying & mask) && ((varying >> 11) & mask) && (varying >> 22)) { std::array, 3> counts{}; for (const auto &value : values) { std::uint32_t k = key(value); ++counts[0][k & mask]; ++counts[1][(k >> 11) & mask]; ++counts[2][k >> 22]; } for (int pass = 0; pass < 3; ++pass) { auto &count = counts[pass]; std::uint32_t sum = 0; for (auto &x : count) { auto n = x; x = sum, sum += n; } for (auto &&value : values) scratch[count[(std::uint32_t(key(value)) >> (11 * pass)) & mask]++] = std::move(value); values.swap(scratch); } return; } } using Counts = std::conditional_t<(Bits <= 11), std::array, std::vector>; Counts count = [] { if constexpr (Bits <= 11) return Counts{}; else return Counts(buckets); }(); for (int shift = 0; shift < 64; shift += Bits) { if (!((varying >> shift) & mask)) continue; std::fill(count.begin(), count.end(), 0); for (const auto &value : values) ++count[(static_cast(key(value)) >> shift) & mask]; std::size_t sum = 0; for (auto &x : count) { auto n = x; x = sum, sum += n; } for (auto &&value : values) scratch[count[(static_cast(key(value)) >> shift) & mask]++] = std::move(value); values.swap(scratch); } } template void stable_radix_sort(std::vector &values, Key key) { stable_radix_sort<8>(values, std::move(key)); } namespace radix_sort_detail { template void sort_by_key(std::vector &values, Key key) { using K = std::remove_cvref_t()))>; if constexpr (std::is_integral_v && !std::is_same_v && sizeof(K) <= 8 && std::is_default_constructible_v) { using U = std::make_unsigned_t; constexpr U sign = std::is_signed_v ? U(1) << (sizeof(K) * 8 - 1) : U(0); stable_radix_sort(values, [&](const T &value) { return U(U(key(value)) ^ sign); }); } else std::sort(values.begin(), values.end(), [&](const T &a, const T &b) { return key(a) < key(b); }); } } #line 6 "sequence/inversion_count.hpp" #include #include #line 10 "sequence/inversion_count.hpp" #include #include #include #line 15 "sequence/inversion_count.hpp" template > requires std::ranges::random_access_range && std::ranges::sized_range && requires(Compare &compare, std::ranges::iterator_t first) { bool(compare(first[0], first[0])); } std::int64_t inversion_count(const Range &a, Compare compare = {}) { assert(std::ranges::size(a) <= std::size_t(std::numeric_limits::max())); const std::size_t n = std::ranges::size(a); auto first = std::ranges::begin(a); std::size_t ordered = 1; while (ordered < n && !compare(first[ordered], first[ordered - 1])) ++ordered; if (ordered >= n) return 0; std::int64_t equal_pairs = 0; std::size_t run = 1, reversed = 1; for (; reversed < n && !compare(first[reversed - 1], first[reversed]); ++reversed) { if (compare(first[reversed], first[reversed - 1])) run = 1; else equal_pairs += static_cast(run++); } if (reversed == n) return static_cast(n) * (n - 1) / 2 - equal_pairs; using T = std::ranges::range_value_t; constexpr bool cached = std::is_trivially_copyable_v && sizeof(T) <= 16 && std::is_default_constructible_v && std::is_copy_constructible_v && std::is_copy_assignable_v && !std::is_same_v; using Stored = std::conditional_t; std::vector current(n), buffer(n); for (std::size_t i = 0; i < n; ++i) { if constexpr (cached) current[i] = first[i]; else current[i] = static_cast(i); } auto value = [&](const Stored &x) -> decltype(auto) { if constexpr (cached) return (x); else return first[x]; }; std::int64_t result = 0; constexpr std::size_t block = 8; for (std::size_t l = 0; l < n; l += block) { const auto end = std::min(l + block, n); for (std::size_t i = l + 1; i < end; ++i) { Stored x = current[i]; std::size_t j = i; while (j > l && compare(value(x), value(current[j - 1]))) current[j] = current[j - 1], --j; current[j] = x; result += static_cast(i - j); } } for (std::size_t width = block; width < n; width *= 2) { for (std::size_t l = 0; l < n; l += 2 * width) { const auto mid = std::min(l + width, n), r = std::min(l + 2 * width, n); if (mid == r || !compare(value(current[mid]), value(current[mid - 1]))) { std::copy(current.begin() + l, current.begin() + r, buffer.begin() + l); continue; } if (compare(value(current[r - 1]), value(current[l]))) { result += static_cast(mid - l) * (r - mid); std::copy(current.begin() + mid, current.begin() + r, buffer.begin() + l); std::copy(current.begin() + l, current.begin() + mid, buffer.begin() + (l + r - mid)); continue; } std::size_t i = l, j = mid, k = l; while (i < mid && j < r) { if (compare(value(current[j]), value(current[i]))) { buffer[k++] = current[j++]; result += static_cast(mid - i); } else buffer[k++] = current[i++]; } std::copy(current.begin() + i, current.begin() + mid, buffer.begin() + k); std::copy(current.begin() + j, current.begin() + r, buffer.begin() + (k + mid - i)); } current.swap(buffer); } return result; } template requires std::ranges::random_access_range && std::ranges::sized_range && std::ranges::random_access_range && std::ranges::sized_range && std::same_as, std::ranges::range_value_t> && std::integral> && (sizeof(std::ranges::range_value_t) <= 8) std::int64_t inversion_count(const A &a, const B &b) { if (std::ranges::size(a) != std::ranges::size(b)) return -1; assert(std::ranges::size(a) <= std::size_t(std::numeric_limits::max())); if (std::ranges::equal(a, b)) return 0; using T = std::ranges::range_value_t; using U = std::make_unsigned_t, unsigned char, T>>; const int n = static_cast(std::ranges::size(a)); auto sorted_positions = [](auto first, int n) { std::vector> positions(n); for (int i = 0; i < n; ++i) positions[i] = {U(first[i]), i}; stable_radix_sort<11>(positions, [](const auto &p) { return p.first; }); return positions; }; auto x = sorted_positions(std::ranges::begin(a), n), y = sorted_positions(std::ranges::begin(b), n); std::vector permutation(n); for (int i = 0; i < n; ++i) { if (x[i].first != y[i].first) return -1; permutation[x[i].second] = y[i].second; } return inversion_count(permutation); } int N = 64; int M = 256; int SCORE_BASE = 256 * 255 / 2; vector A(M); void input() { cin >> N; cin >> A; } constexpr int dr[4] = {-1, 0, 1, 0}; constexpr int dc[4] = {0, 1, 0, -1}; constexpr int paired[3][4] = { {2, 3, 0, 1}, // 直進 {3, 2, 1, 0}, // / {1, 0, 3, 2}, // \. }; class Solver { struct State { int score; vector S; vector B; State() { score = 0; S.resize(N); for (int i = 0; i < N; i++) { S[i] = string(N, '0'); } B = calc_B(); calc_score(); } void calc_score() { score = inversion_count(B); } int end_point(int r, int c, int dir) { while (0 <= r && r < N && 0 <= c && c < N) { int mirror_type = S[r][c] - '0'; int entered_from = (dir + 2) % 4; int leaves_through = paired[mirror_type][entered_from]; dir = leaves_through; r += dr[dir]; c += dc[dir]; } if (r < 0) return c; // 上辺 if (c >= N) return N + r; // 右辺 if (r >= N) return 3 * N - 1 - c; // 下辺 return 4 * N - 1 - r; // 左辺 } vector calc_B() { vector B(M, 0); for (int edge = 0; edge < 4; edge++) { int into = (edge + 2) % 4; for (int i = 0; i < N; i++) { int p = edge * N + i; if (B[p] != 0) continue; const int START_R[4] = {0, i, N - 1, N - 1 - i}; const int START_C[4] = {i, N - 1, N - 1 - i, 0}; int q = end_point(START_R[edge], START_C[edge], into); B[q] = A[p]; B[p] = A[q]; } } return B; } }; State current; State best; public: void init() { } void solve() { while (get_time_global() < 1900) { int r = rand_int(0, N); int c = rand_int(0, N); char &mirror = current.S[r][c]; char before_mirror = mirror; int new_mirror = (before_mirror - '0' + rand_int(1, 3)) % 3; mirror = char('0' + new_mirror); vector new_B = current.calc_B(); int next_score = inversion_count(new_B); if (next_score >= current.score) { mirror = before_mirror; continue; } current.B = new_B; current.score = next_score; } best = current; } void output() { // bestを出力 for (int i = 0; i < N; i++) { cout << best.S[i] << endl; } } }; signed main() { start_timer(); // get_time_global() で時間を取得可能 input(); Solver solver = Solver(); solver.init(); solver.solve(); solver.output(); // AHC_REPORT(); } /* 21:10 せっかくなので紙ではなくここで考察 (A_0, ..., A_{M-1})をできる限り(B_0, ..., B_{M-1})に近づける 1つのマスの鏡の状態を変化させた時、高々2個分のdeleteとinsertのみ(そうじゃなかったら、同じ終着点に着くレーザーが2本以上存在してしまうことになる) それってシンプルな焼きなましが可能そう? 実際、ビジュアライザー上で鏡を適当に一つ操作すると、スコアの変化量はかなり小さい。鏡を置く/消す/向きを変える操作がそのまま近傍として利用できそう! 21:20 強い配置が存在する? 正直これは思いつかない(し、コンテスト時間を考えるとこれを考え続けるのは少しギャンブル) 初期状態を無配置状態、近傍を鏡を置く/消す/向きを変える→(ある1点を選択して、鏡の状態をランダムに変化させる)とする。 選択する鏡を、完全な無作為選択にするのではなく、既に正しい場所に光を導けている鏡は少し選択されにくくするような工夫ができそう 21:25 実装に入る 転倒数の計算がボトルネックになりそうだから、高速化を頑張っているらしいライブラリから持ってくる。 https://qandori.github.io/cp-library/sequence/inversion_count.hpp.html 22:33 ようやく山登り方の実装が終了 Average Score : 28,439.56 めちゃくちゃ上振れますように */