// #pragma GCC target("avx2") // #pragma GCC optimize("O3") // #pragma GCC optimize("unroll-loops") #include #include #include using namespace std; using namespace __gnu_pbds; // #include // using mint = atcoder::modint998244353; using ll = long long; #define rep(i, n) for (ll i = 0; i < (ll)(n); ++i) // const ll dy[] = {-1, -1, -1, 0, 0, 1, 1, 1}; // const ll dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; const ll dy[] = {-1, 0, 0, 1}; const ll dx[] = {0, -1, 1, 0}; template T min(const T &t, const U &u) { return t < u ? t : u; } template T max(const T &t, const U &u) { return t < u ? u : t; } template bool chmin(T &t, const U &u) { if (t > u) { t = u; return true; } return false; } template bool chmax(T &t, const U &u) { if (t < u) { t = u; return true; } return false; } template using hash_map = gp_hash_table; template using hash_set = gp_hash_table; // #include "titan_cpplib/others/io.cpp" // #include "titan_cpplib/others/print.cpp" /// https://github.com/titan-23/Library_cpp/blob/main/titan_cpplib/others/print.cpp #include using namespace std; // print // ------------------------- // pair template ostream& operator<<(ostream& os, const pair& p); // tuple template ostream &operator<<(ostream &os, const tuple &t); // tuple template ostream &operator<<(ostream &os, const tuple &t); // vector template ostream& operator<<(ostream& os, const vector& a); // vector> template ostream& operator<<(ostream& os, const vector>& a); // array template ostream& operator<<(ostream &os, const array &a); // stack template ostream& operator<<(ostream& os, const stack& s); // queue template ostream& operator<<(ostream& os, const queue& q); // deque template ostream& operator<<(ostream& os, const deque& dq); // priority_queue template ostream& operator<<(ostream& os, const priority_queue& pq); // set template ostream& operator<<(ostream& os, const set& s); // multiset template ostream& operator<<(ostream& os, const multiset& s); // unordered_set template ostream& operator<<(ostream& os, const unordered_set& a); // map template ostream& operator<<(ostream& os, const map& mp); // unordered_map template ostream& operator<<(ostream& os, const unordered_map& mp); // __int128_t ostream& operator<<(ostream& os, __int128_t x); // __uint128_t ostream& operator<<(ostream& os, __uint128_t x); // ------------------------- // color static const string PRINT_RED = "\033[91m"; // 赤字 static const string PRINT_GREEN = "\033[92m"; // 緑字 static const string PRINT_YELLOW = "\033[93m"; // 黄字 static const string PRINT_BLUE = "\033[94m"; // 青字 static const string PRINT_DIM = "\033[2m"; // 薄字 static const string PRINT_NONE = "\033[m"; // 色を元に戻す static const string PRINT_BOLD = "\u001b[1m"; // 太字 /// @brief s を関数名が示す色や書式の制御文字列で囲んで返す string to_red (const string &s) { return PRINT_RED + s + PRINT_NONE; } string to_green (const string &s) { return PRINT_GREEN + s + PRINT_NONE; } string to_yellow(const string &s) { return PRINT_YELLOW + s + PRINT_NONE; } string to_blue (const string &s) { return PRINT_BLUE + s + PRINT_NONE; } string to_dim (const string &s) { return PRINT_DIM + s + PRINT_NONE; } string to_bold (const string &s) { return PRINT_BOLD + s + PRINT_NONE; } /// @brief s の左を空白で埋めて幅 f にする string spacefill(const string s, const int f) { int n = s.size(); string t; for (int i = 0; i < f-n; ++i) t += " "; t += s; return t; } /// @brief x を to_string で文字列にし、左を空白で埋めて幅 f にする template string spacefill(const T &x, const int f) { return spacefill(to_string(x), f); } /// @brief s の左を 0 で埋めて幅 f にする string zfill(const string s, const int f) { int n = s.size(); string t; for (int i = 0; i < f-n; ++i) t += "0"; t += s; return t; } /// @brief s の 2 進表記を返す string bin(unsigned long long s) { if (s == 0) return "0"; string t; while (s) { t += (s & 1) ? '1' : '0'; s >>= 1; } reverse(t.begin(), t.end()); return t; } // 現在の行番号を標準エラー出力に出す #define DEBUG_LINE() (cerr << "[LINE] : " << __LINE__ << endl) /// @brief __int128_t を 10 進表記の文字列にする string to_string_int128(__int128_t x) { if (x == 0) return "0"; bool neg = false; if (x < 0) { neg = true; x = -x; } string s; while (x > 0) { s += char('0' + (int)(x % 10)); x /= 10; } if (neg) s += '-'; reverse(s.begin(), s.end()); return s; } /// @brief __uint128_t を 10 進表記の文字列にする string to_string_uint128(__uint128_t x) { if (x == 0) return "0"; string s; while (x > 0) { s += char('0' + (int)(x % 10)); x /= 10; } reverse(s.begin(), s.end()); return s; } // __int128_t ostream& operator<<(ostream& os, __int128_t x) { os << to_string_int128(x); return os; } // __uint128_t ostream& operator<<(ostream& os, __uint128_t x) { os << to_string_uint128(x); return os; } // pair template ostream& operator<<(ostream& os, const pair& p) { os << "(" << p.first << ", " << p.second << ")"; return os; } // tuple template ostream &operator<<(ostream &os, const tuple &t) { os << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ")"; return os; } // tuple template ostream &operator<<(ostream &os, const tuple &t) { os << "(" << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << ", " << get<3>(t) << ")"; return os; } // array template ostream& operator<<(ostream &os, const array &a) { os << "["; for (int i = 0; i < (int)N; ++i) { if (i > 0) os << ", "; os << a[i]; } os << "]"; return os; } // vector template ostream& operator<<(ostream& os, const vector& a) { os << "["; for (int i = 0; i < (int)a.size(); ++i) { if (i > 0) os << ", "; os << a[i]; } os << "]"; return os; } // vector> template ostream& operator<<(ostream& os, const vector>& a) { os << "[\n"; int h = (int)a.size(); for (int i = 0; i < h; ++i) { os << " " << a[i] << '\n'; } os << "]"; return os; } // stack template ostream& operator<<(ostream& os, const stack& s) { stack tmp = s; vector v; while (!tmp.empty()) { v.push_back(tmp.top()); tmp.pop(); } os << "["; for (int i = (int)v.size()-1; i >= 0; --i) { if (i != (int)v.size()-1) os << ", "; os << v[i]; } os << "]"; return os; } // queue template ostream& operator<<(ostream& os, const queue& q) { queue tmp = q; os << "["; bool first = true; while (!tmp.empty()) { if (!first) os << ", "; first = false; os << tmp.front(); tmp.pop(); } os << "]"; return os; } // deque template ostream& operator<<(ostream& os, const deque& dq) { vector a(dq.begin(), dq.end()); os << a; return os; } // priority_queue template ostream& operator<<(ostream& os, const priority_queue& pq) { priority_queue tmp = pq; os << "["; bool first = true; while (!tmp.empty()) { if (!first) os << ", "; first = false; os << tmp.top(); tmp.pop(); } os << "]"; return os; } // set template ostream& operator<<(ostream& os, const set& s) { os << "{"; auto it = s.begin(); while (it != s.end()) { os << *it; ++it; if (it != s.end()) { os << ", "; } } os << "}"; return os; } // multiset template ostream& operator<<(ostream& os, const multiset& s) { os << "{"; auto it = s.begin(); while (it != s.end()) { os << *it; ++it; if (it != s.end()) { os << ", "; } } os << "}"; return os; } // unordered_set template ostream& operator<<(ostream& os, const unordered_set& a) { set s(a.begin(), a.end()); os << s; return os; } // map template ostream& operator<<(ostream& os, const map& mp) { os << "{"; auto it = mp.begin(); while (it != mp.end()) { os << it->first << ": " << it->second; ++it; if (it != mp.end()) { os << ", "; } } os << "}"; return os; } // unordered_map template ostream& operator<<(ostream& os, const unordered_map& mp) { map m(mp.begin(), mp.end()); os << m; return os; } constexpr const int N = 64; constexpr const int M = 4*N; array A; bool isrange(int i, int j) { return 0 <= i && i < N && 0 <= j && j < N; } void input() { int n; cin >> n; rep(i, M) cin >> A[i]; } /// https://github.com/titan-23/Library_cpp/blob/main/titan_cpplib/ahc/sa/sa_state.cpp // OMP_NUM_THREADS=32 time ./a.out < in/0000.txt > out.txt #include // #include "titan_cpplib/ahc/timer.cpp" /// https://github.com/titan-23/Library_cpp/blob/main/titan_cpplib/ahc/timer.cpp #include #include using namespace std; // Timer namespace titan23 { /// @brief 経過時間を計測する class Timer { private: chrono::time_point start_timepoint; public: /// @brief 構築した時刻から計測を始める Timer() : start_timepoint(chrono::high_resolution_clock::now()) {} /// @brief 計測の起点を現在の時刻に戻す void reset() { start_timepoint = chrono::high_resolution_clock::now(); } /// @brief 起点からの経過時間を ms 単位の double で返す double elapsed() const { // auto end_timepoint = chrono::high_resolution_clock::now(); // auto start = chrono::time_point_cast(start_timepoint).time_since_epoch().count(); // auto end = chrono::time_point_cast(end_timepoint).time_since_epoch().count(); // return (end - start) * 0.001; auto end_timepoint = std::chrono::high_resolution_clock::now(); std::chrono::duration duration = end_timepoint - start_timepoint; return duration.count(); } }; } // namespace titan23 // #include "titan_cpplib/alg/random.cpp" /// https://github.com/titan-23/Library_cpp/blob/main/titan_cpplib/alg/random.cpp #include #include #include #include #include #include #include #include using namespace std; namespace titan23 { /// @brief XOR shift による擬似乱数生成器 class Random { private: uint32_t _x, _y, _z, _w; constexpr uint32_t _xor128() { const uint32_t t = _x ^ (_x << 11); _x = _y; _y = _z; _z = _w; _w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8)); return _w; } public: /// @brief 固定の初期状態で構築する Random() : _x(123456789), _y(362436069), _z(521288629), _w(88675123) {} /// @brief seed で構築する Random(uint32_t seed) { set_seed(seed); } /// @brief seed で状態を初期化する void set_seed(uint32_t seed) { _x = seed; _y = _x * 1812433253U + 1; _z = _y * 1812433253U + 1; _w = _z * 1812433253U + 1; } /// @brief [0, 1] の実数の乱数を返す constexpr double random() { return (double)(_xor128()) / 0xFFFFFFFF; } /// @brief [0, end] の整数の乱数を返す constexpr int randint(const int end) { assert(0 <= end); return (((uint64_t)_xor128() * ((uint64_t)end + 1)) >> 32); } /// @brief [begin, end] の整数の乱数を返す constexpr int randint(const int begin, const int end) { assert(begin <= end); return begin + (((uint64_t)_xor128() * ((uint64_t)end - begin + 1)) >> 32); } /// @brief [0, end) の整数の乱数を返す constexpr int randrange(const int end) { assert(0 < end); return (((uint64_t)_xor128() * end) >> 32); } /// @brief [begin, end) の整数の乱数を返す constexpr int randrange(const int begin, const int end) { assert(begin < end); return begin + (((uint64_t)_xor128() * (end-begin)) >> 32); } /// @brief [0, u64_MAX] の乱数を返す / Zobrist hash などでの使用を想定 constexpr uint64_t rand_u64() { return ((uint64_t)_xor128() << 32) | _xor128(); } /// @brief [0, end) の 64 bit 整数の乱数を返す constexpr long long randrange_ll(const long long end) { assert(0 < end); return (long long)(((__uint128_t)rand_u64() * (uint64_t)end) >> 64); } /// @brief [begin, end) の 64 bit 整数の乱数を返す constexpr long long randrange_ll(const long long begin, const long long end) { assert(begin < end); return begin + (long long)(((__uint128_t)rand_u64() * (uint64_t)(end-begin)) >> 64); } /// @brief [0, end) から相異なる 2 つの乱数を小さい順に返す constexpr pair rand_pair(const int end) { assert(end >= 2); int u = randrange(end); int v = u + randrange(1, end); if (v >= end) v -= end; if (u > v) swap(u, v); return {u, v}; } /// @brief [begin, end) から相異なる 2 つの乱数を小さい順に返す constexpr pair rand_pair(const int begin, const int end) { assert(end - begin >= 2); int u = randrange(begin, end); int v = (u + randrange(1, end-begin)); if (v >= end) v -= (end-begin); if (u > v) swap(u, v); return {u, v}; } /// @brief a から重複なしで cnt 個を無作為に選んで返す / 選んだ要素を a の先頭へ移すので a は書き換わる / O(cnt) vector rand_vec(const int cnt, vector &a) { int n = a.size(); for (int i = 0; i < cnt; ++i) { int j = randrange(i, n); swap(a[i], a[j]); } vector res(a.begin(), a.begin()+cnt); return res; } /// @brief [begin, end] の実数の乱数を返す constexpr double randdouble(const double begin, const double end) { assert(begin <= end); return begin + random() * (end-begin); } /// @brief [first, last) を無作為に並べ替える / O(n) template void shuffle(RandomIt first, RandomIt last) { int n = distance(first, last); for (int i = 0; i < n-1; ++i) { int j = randrange(i, n); iter_swap(first+i, first+j); } } /// @brief a をその場で無作為に並べ替える / O(n) template void shuffle(vector &a) { shuffle(a.begin(), a.end()); } /// @brief a から重複なしで k 個を無作為に選んで返す / O(n) template vector choices(const vector &a, const int k) { int n = a.size(); assert(n >= k); vector idx(n); iota(idx.begin(), idx.end(), 0); for (int i = 0; i < k; ++i) { int j = randrange(i, n); swap(idx[i], idx[j]); } vector r(k); for (int i = 0; i < k; ++i) { r[i] = a[idx[i]]; } return r; } /// @brief a から無作為に 1 要素を選んで返す / O(1) template constexpr T choice(const vector &a) { assert(!a.empty()); return a[randrange(a.size())]; } /// @brief 重み w に従って a から 1 要素を選んで返す / O(n) template constexpr T choice(const vector &a, const vector &w) { assert(a.size() == w.size()); double sum = 0.0; for (const int &x: w) sum += x; assert(sum > 0); vector x(w.size()); for (int i = 0; i < x.size(); ++i) { x[i] = (double)w[i] / sum; if (i-1 >= 0) x[i] += x[i-1]; } if (!x.empty()) x.back() = 1.0; return choice(a, x); } /// @brief 累積確率分布 w に従って a から 1 要素を選んで返す / O(log n) template constexpr T choice(const vector &a, const vector &w) { double i = random(); int l = -1, r = a.size()-1; while (r - l > 1) { int mid = (l + r) / 2; if (w[mid] <= i) l = mid; else r = mid; } return a[r]; } /// @brief a から無作為に 1 要素を取り除いて返す / O(n) template constexpr T rand_pop(vector &a) { assert(!a.empty()); int idx = randrange(a.size()); T res = a[idx]; a.erase(a.begin() + idx); return res; } }; } // namespace titan23 // #include "titan_cpplib/ahc/sa/sa.cpp" /// https://github.com/titan-23/Library_cpp/blob/main/titan_cpplib/ahc/sa/sa.cpp // OMP_NUM_THREADS=32 time ./a.out < in/0000.txt > out.txt #include #include using namespace std; // 焼きなまし法。スコアを最小化する namespace sa { // LOG_TABLE[i] = log((i + 0.5) / LOG_TABLE_SIZE)。受理の閾値を乱数から作るのに使う const int LOG_TABLE_SIZE = 4096; double LOG_TABLE[LOG_TABLE_SIZE]; static bool is_log_initialized = [] { for (int i = 0; i < LOG_TABLE_SIZE; ++i) { LOG_TABLE[i] = log((double)(i + 0.5) / LOG_TABLE_SIZE); } return true; }(); /// @brief 初期化済みの state から焼きなましを実行し、最良解を返す / TIME_LIMIT は実行時間 [ms]、verbose はログ出力の有無 template typename State::Result sa_run(const double TIME_LIMIT, State& state, const bool verbose=true) { titan23::Timer sa_timer; typename State::Result best_result = state.get_result(); if (TIME_LIMIT <= 0) return best_result; titan23::Random sa_rnd; const double START_TEMP = State::param.start_temp; const double END_TEMP = max(State::param.end_temp, 1e-9); const int TEMP_TABLE_SIZE = 4096; vector TEMP_TABLE(TEMP_TABLE_SIZE); for (int i = 0; i < TEMP_TABLE_SIZE; ++i) { TEMP_TABLE[i] = START_TEMP * pow(END_TEMP / START_TEMP, (double)i / (TEMP_TABLE_SIZE - 1)); } int64_t iter = 0, bst_cnt = 0, upd_cnt = 0; int64_t valid_cnt = 0; vector accept(state.changed.TYPE_CNT), accept_worse(state.changed.TYPE_CNT), modify(state.changed.TYPE_CNT); double now_time = 0; typename State::ScoreType score = best_result.score; if (verbose) { cerr << "init-fin" << endl; cerr << "init-time = " << sa_timer.elapsed() << endl; cerr << "init-score = " << best_result.true_score << " (" << best_result.score << ")" << endl; cerr << "--------" << endl; } const double search_start = sa_timer.elapsed(); const double search_time = TIME_LIMIT - search_start; if (search_time <= 0) return best_result; while (true) { // if ((iter & 31) == 0) now_time = sa_timer.elapsed(); now_time = sa_timer.elapsed(); if (now_time >= TIME_LIMIT) break; ++iter; double progress = (now_time - search_start) / search_time; // 線形冷却 // typename State::ScoreType threshold = score - (START_TEMP-(START_TEMP-END_TEMP)*progress) * LOG_TABLE[sa_rnd.randrange(LOG_TABLE_SIZE)]; // 指数冷却 int temp_idx = (int)(progress * (TEMP_TABLE_SIZE - 1)); double now_temp = TEMP_TABLE[temp_idx]; typename State::ScoreType threshold = score - now_temp * LOG_TABLE[sa_rnd.randrange(LOG_TABLE_SIZE)]; state.reset_is_valid(); state.modify(iter, threshold, progress); modify[state.changed.type]++; typename State::ScoreType new_score = state.get_score(); if (state.is_valid) valid_cnt++; if (state.is_valid && new_score <= threshold) { ++upd_cnt; accept[state.changed.type]++; if (new_score > score) accept_worse[state.changed.type]++; state.advance(); score = new_score; if (score < best_result.score) { bst_cnt++; best_result = state.get_result(); if (verbose) { cerr << "Info: score=" << best_result.true_score << " (" << best_result.score << ")" << " | time=" << now_time << " | prog=" << (progress * 100.0) << "%" << " | temp=" << now_temp << endl; } } } else { state.rollback(); state.score = score; } } if (verbose) { double total_time = sa_timer.elapsed(); cerr << "=============" << endl; for (int i = 0; i < (int)modify.size(); ++i) { double accept_rate = (modify[i] > 0) ? ((double)accept[i] / modify[i] * 100.0) : 0.0; double worse_rate = (accept[i] > 0) ? ((double)accept_worse[i] / accept[i] * 100.0) : 0.0; cerr << "Info: Type=" << i << " | " << accept[i] << " / " << modify[i] << " (" << accept_rate << "%)" << " | worse=" << accept_worse[i] << " / " << accept[i] << " (" << worse_rate << "%)" << endl; } cerr << "Info: bst=" << bst_cnt << endl; cerr << "Info: ac=" << upd_cnt << endl; cerr << "Info: loop=" << iter << endl; cerr << "Info: valid_cnt=" << valid_cnt << ", " << (iter > 0 ? (int)((double)valid_cnt/iter*100) : 0) << "%" << endl; cerr << "Info: accept rate=" << (iter > 0 ? (int)((double)upd_cnt/iter*100) : 0) << "%" << endl; cerr << "Info: update best rate=" << (iter > 0 ? (int)((double)bst_cnt/iter*100) : 0) << "%" << endl; cerr << "Info: best_score = " << best_result.true_score << " (" << best_result.score << ")" << endl; cerr << "Info: total_time = " << total_time << " ms" << endl; cerr << "Info: ips = " << (total_time > 0 ? iter * 1000.0 / total_time : 0.0) << endl; } return best_result; } /// @brief State を seed で初期化して焼きなましを実行し、最良解を返す / TIME_LIMIT は初期化を含む実行時間 [ms] template typename State::Result sa_run(const double TIME_LIMIT, const uint32_t seed=23, const bool verbose=true) { titan23::Timer timer; State state; state.init(seed); const double remaining_time = TIME_LIMIT - timer.elapsed(); return sa_run(remaining_time, state, verbose); } /// @brief 2 段階の多始点焼きなましを実行し、最良解を返す / TIME_LIMIT は実行時間 [ms] /// 第 1 段階は TIME_LIMIT * FIRST_PHASE_RATIO の時間で NUM_STARTS 個の初期状態を順に焼きなまし、第 2 段階はその最良の状態から続ける template typename State::Result sa_multi_run( const double TIME_LIMIT, const double FIRST_PHASE_RATIO, const int NUM_STARTS, const uint32_t seed = 23, const bool verbose = true) { titan23::Timer sa_timer; titan23::Random sa_rnd; const double phase1_time_limit = TIME_LIMIT * FIRST_PHASE_RATIO; const double time_per_start = phase1_time_limit / NUM_STARTS; const double START_TEMP = State::param.start_temp; const double END_TEMP = max(State::param.end_temp, 1e-9); const int TEMP_TABLE_SIZE = 4096; vector TEMP_TABLE(TEMP_TABLE_SIZE); for (int i = 0; i < TEMP_TABLE_SIZE; ++i) { TEMP_TABLE[i] = START_TEMP * pow(END_TEMP / START_TEMP, (double)i / (TEMP_TABLE_SIZE - 1)); } State best_overall_state; typename State::Result best_overall_result; bool is_first = true; for (int i = 0; i < NUM_STARTS; ++i) { State state; state.init(seed + i); State best_local_state = state; typename State::Result best_local_result = state.get_result(); typename State::ScoreType score = best_local_result.score; int64_t iter = 0; double start_time = sa_timer.elapsed(); double now_time = start_time; while (true) { now_time = sa_timer.elapsed(); if (now_time - start_time > time_per_start) break; ++iter; double progress = (now_time - start_time) / time_per_start; if (progress > 1.0) progress = 1.0; int temp_idx = (int)(progress * (TEMP_TABLE_SIZE - 1)); double now_temp = TEMP_TABLE[temp_idx]; typename State::ScoreType threshold = score - now_temp * LOG_TABLE[sa_rnd.randrange(LOG_TABLE_SIZE)]; state.reset_is_valid(); state.modify(iter, threshold, progress); typename State::ScoreType new_score = state.get_score(); if (state.is_valid && new_score <= threshold) { state.advance(); score = new_score; if (score < best_local_result.score) { best_local_result = state.get_result(); best_local_state = state; } } else { state.rollback(); state.score = score; } } if (is_first || best_local_result.score < best_overall_result.score) { best_overall_state = best_local_state; best_overall_result = best_local_result; is_first = false; } } if (verbose) { cerr << "--- Phase 1 finish ---" << endl; cerr << "Best score in Phase 1: " << best_overall_result.true_score << " (" << best_overall_result.score << ")" << endl; cerr << "Elapsed time: " << sa_timer.elapsed() << " ms" << endl; } State state = best_overall_state; typename State::Result best_result = best_overall_result; typename State::ScoreType score = state.get_score(); int64_t iter = 0, bst_cnt = 0, upd_cnt = 0, valid_cnt = 0; vector accept(state.changed.TYPE_CNT), accept_worse(state.changed.TYPE_CNT), modify(state.changed.TYPE_CNT); double start_time = sa_timer.elapsed(); double now_time = start_time; double phase2_time_limit = TIME_LIMIT - start_time; if (phase2_time_limit <= 0) return best_result; const double phase2_start_temp = START_TEMP * pow(END_TEMP / START_TEMP, FIRST_PHASE_RATIO); vector PHASE2_TEMP_TABLE(TEMP_TABLE_SIZE); for (int i = 0; i < TEMP_TABLE_SIZE; ++i) { PHASE2_TEMP_TABLE[i] = phase2_start_temp * pow(END_TEMP / phase2_start_temp, (double)i / (TEMP_TABLE_SIZE - 1)); } while (true) { now_time = sa_timer.elapsed(); if (now_time > TIME_LIMIT) break; ++iter; double progress = (now_time - start_time) / phase2_time_limit; if (progress > 1.0) progress = 1.0; int temp_idx = (int)(progress * (TEMP_TABLE_SIZE - 1)); double now_temp = PHASE2_TEMP_TABLE[temp_idx]; typename State::ScoreType threshold = score - now_temp * LOG_TABLE[sa_rnd.randrange(LOG_TABLE_SIZE)]; state.reset_is_valid(); state.modify(iter, threshold, progress); modify[state.changed.type]++; typename State::ScoreType new_score = state.get_score(); if (state.is_valid) valid_cnt++; if (state.is_valid && new_score <= threshold) { ++upd_cnt; accept[state.changed.type]++; if (new_score > score) accept_worse[state.changed.type]++; state.advance(); score = new_score; if (score < best_result.score) { bst_cnt++; best_result = state.get_result(); if (verbose) { cerr << "Info: score=" << best_result.true_score << " (" << best_result.score << ")" << " | time=" << now_time << " | prog=" << (progress * 100.0) << "%" << " | temp=" << now_temp << endl; } } } else { state.rollback(); state.score = score; } } if (verbose) { double total_time = sa_timer.elapsed(); cerr << "=============" << endl; cerr << "--- Phase 2 finish ---" << endl; for (int i = 0; i < (int)modify.size(); ++i) { double accept_rate = (modify[i] > 0) ? ((double)accept[i] / modify[i] * 100.0) : 0.0; double worse_rate = (accept[i] > 0) ? ((double)accept_worse[i] / accept[i] * 100.0) : 0.0; cerr << "Info: Type=" << i << " | " << accept[i] << " / " << modify[i] << " (" << accept_rate << "%)" << " | worse=" << accept_worse[i] << " / " << accept[i] << " (" << worse_rate << "%)" << endl; } cerr << "Info: bst=" << bst_cnt << endl; cerr << "Info: ac=" << upd_cnt << endl; cerr << "Info: loop=" << iter << endl; cerr << "Info: valid_cnt=" << valid_cnt << ", " << (iter > 0 ? (int)((double)valid_cnt/iter*100) : 0) << "%" << endl; cerr << "Info: accept rate=" << (iter > 0 ? (int)((double)upd_cnt/iter*100) : 0) << "%" << endl; cerr << "Info: update best rate=" << (iter > 0 ? (int)((double)bst_cnt/iter*100) : 0) << "%" << endl; cerr << "Info: best_score = " << best_result.true_score << " (" << best_result.score << ")" << endl; cerr << "Info: total_time = " << total_time << " ms" << endl; cerr << "Info: ips = " << (total_time > 0 ? iter * 1000.0 / total_time : 0.0) << endl; } return best_result; } /// @brief NUM_REPLICAS 個の状態でレプリカ交換法を実行し、最良解を返す / 状態は OpenMP で並列に動くので、状態の間で可変のデータを共有しない /// SWAP_ITER_INTERVAL 回の反復ごとに熱浴を交換する。record が true なら replica_scores.csv と best_state_*.txt に記録する template typename State::Result replica_run( const double TIME_LIMIT, const int NUM_REPLICAS=32, const int SWAP_ITER_INTERVAL=100, const bool verbose=true, const bool record=false, const uint32_t seed=23 ) { titan23::Timer sa_timer; auto make_seed = [seed](const uint64_t stream_id) -> uint32_t { uint64_t z = (static_cast(seed) << 32) ^ stream_id; z += 0x9e3779b97f4a7c15ULL; z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; z ^= z >> 31; return static_cast(z ^ (z >> 32)); }; struct alignas(64) PaddedRandom { titan23::Random value; }; vector accept_rnd(NUM_REPLICAS); vector state_seeds(NUM_REPLICAS); for (int i = 0; i < NUM_REPLICAS; ++i) { state_seeds[i] = make_seed(2ULL * i); accept_rnd[i].value.set_seed(make_seed(2ULL * i + 1)); } titan23::Random swap_rnd(make_seed(UINT64_MAX)); vector temps(NUM_REPLICAS); for (int i = 0; i < NUM_REPLICAS; ++i) { temps[i] = State::param.start_temp * pow(State::param.end_temp / State::param.start_temp, (double)i / max(1, NUM_REPLICAS-1)); } vector states(NUM_REPLICAS); vector rep_idx(NUM_REPLICAS); vector scores(NUM_REPLICAS); vector iter(NUM_REPLICAS, 0); #pragma omp parallel { #pragma omp for schedule(static) for (int i = 0; i < NUM_REPLICAS; ++i) { states[i].init(state_seeds[i]); rep_idx[i] = i; scores[i] = states[i].get_score(); } } int max_threads = omp_get_max_threads(); int type_cnt = max(1, states[0].changed.TYPE_CNT); vector> accept(max_threads, vector(type_cnt, 0)); vector> accept_worse(max_threads, vector(type_cnt, 0)); vector> modify(max_threads, vector(type_cnt, 0)); int best_idx = 0; for (int i = 1; i < NUM_REPLICAS; ++i) { if (scores[i] < scores[best_idx]) best_idx = i; } typename State::Result best_result = states[best_idx].get_result(); scores[best_idx] = best_result.score; if (verbose) { cerr << "init-fin" << endl; cerr << "init-time = " << sa_timer.elapsed() << endl; cerr << "init-score = " << best_result.true_score << " (" << best_result.score << ")" << endl; cerr << "--------" << endl; } int64_t swap_cnt = 0; int64_t swap_attempt_total = 0; int64_t swap_accept_total = 0; int64_t total_iter = 0; double now_time = sa_timer.elapsed(); vector thread_best_results(max_threads, best_result); ofstream score_log; string timestamp_str = ""; if (record) { string log_filename = "replica_scores.csv"; score_log.open(log_filename); if (score_log.is_open()) { score_log << "time_ms"; for (int i = 0; i < NUM_REPLICAS; ++i) { score_log << ",temp_" << i << "_score"; } score_log << "\n"; } } int record_num = 0; using TrueScoreType = decay_t().get_true_score())>; vector record_scores(NUM_REPLICAS); double last_print_time = 0.0; const double PRINT_INTERVAL = 10000.0; // 10 秒 while (now_time < TIME_LIMIT) { double block_start_time = now_time; #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for schedule(static) for (int i = 0; i < NUM_REPLICAS; ++i) { int r = rep_idx[i]; double now_temp = temps[i]; double progress = now_time / TIME_LIMIT; typename State::ScoreType cur_score = scores[r]; int64_t local_iter = iter[r]; titan23::Random &rnd = accept_rnd[i].value; for (int step = 0; step < SWAP_ITER_INTERVAL; ++step) { typename State::ScoreType threshold = cur_score - now_temp * LOG_TABLE[rnd.randrange(LOG_TABLE_SIZE)]; states[r].reset_is_valid(); states[r].modify(local_iter, threshold, progress); ++local_iter; modify[tid][states[r].changed.type]++; typename State::ScoreType new_score = states[r].get_score(); if (states[r].is_valid && new_score <= threshold) { bool accepted_worse = new_score > cur_score; states[r].advance(); cur_score = new_score; accept[tid][states[r].changed.type]++; if (accepted_worse) accept_worse[tid][states[r].changed.type]++; if (new_score < thread_best_results[tid].score) { thread_best_results[tid] = states[r].get_result(); } } else { states[r].rollback(); states[r].score = cur_score; } } scores[r] = cur_score; iter[r] = local_iter; } } total_iter += (int64_t)NUM_REPLICAS * SWAP_ITER_INTERVAL; now_time = sa_timer.elapsed(); double block_time = now_time - block_start_time; for (int tid = 0; tid < max_threads; ++tid) { if (thread_best_results[tid].score < best_result.score) { best_result = thread_best_results[tid]; } } if (now_time > TIME_LIMIT) break; if (record) { if (score_log.is_open()) { #pragma omp parallel for schedule(static) for (int i = 0; i < NUM_REPLICAS; ++i) { record_scores[i] = states[rep_idx[i]].get_true_score(); } score_log << now_time; for (int i = 0; i < NUM_REPLICAS; ++i) { score_log << "," << record_scores[i]; } score_log << "\n"; } if (now_time - last_print_time >= PRINT_INTERVAL) { last_print_time = now_time; ostringstream oss_file; oss_file << "best_state_" << record_num << ".txt"; record_num++; ofstream out_state(oss_file.str()); if (out_state.is_open()) { best_result.print(out_state); out_state.close(); } } } if (verbose) { if (swap_cnt % 100 == 0) { cerr << "Info: swap=" << swap_cnt << " | time=" << (int)now_time << "ms" << " | block_time=" << block_time << "ms" << " | best_score=" << best_result.true_score << " (" << best_result.score << ")" << endl; } } int offset = swap_cnt % 2; for (int i = offset; i+1 < NUM_REPLICAS; i += 2) { int r1 = rep_idx[i], r2 = rep_idx[i+1]; double T1 = temps[i]; double T2 = temps[i+1]; typename State::ScoreType E1 = scores[r1]; typename State::ScoreType E2 = scores[r2]; double delta = (static_cast(E1) - static_cast(E2)) * (1.0 / T1 - 1.0 / T2); bool do_swap = delta >= 0.0 || LOG_TABLE[swap_rnd.randrange(LOG_TABLE_SIZE)] < delta; swap_attempt_total++; if (do_swap) { swap(rep_idx[i], rep_idx[i+1]); swap_accept_total++; } } swap_cnt++; } if (record && score_log.is_open()) { score_log.close(); } if (verbose) { double total_time = sa_timer.elapsed(); cerr << "=== Replica Exchange Log ===" << endl; cerr << "Total iterations : " << total_iter << endl; cerr << "Total time : " << total_time << " ms" << endl; cerr << "ips : " << (total_time > 0 ? total_iter * 1000.0 / total_time : 0.0) << endl; cerr << "--- Accept Rates by Type ---" << endl; for (int t = 0; t < type_cnt; ++t) { int64_t total_acc = 0, total_mod = 0, total_worse = 0; for (int tid = 0; tid < max_threads; ++tid) { total_acc += accept[tid][t]; total_mod += modify[tid][t]; total_worse += accept_worse[tid][t]; } if (total_mod > 0) { double worse_rate = (total_acc > 0) ? ((double)total_worse / total_acc * 100.0) : 0.0; cerr << " Type[" << t << "] : " << total_acc << " / " << total_mod << " (" << (double)total_acc / total_mod * 100.0 << "%)" << " | worse=" << total_worse << " / " << total_acc << " (" << worse_rate << "%)" << endl; } } cerr << "Swap attempts : " << swap_attempt_total << endl; cerr << "Swap accepts : " << swap_accept_total << " (" << (swap_attempt_total > 0 ? (double)swap_accept_total / swap_attempt_total * 100.0 : 0.0) << "%)" << endl; cerr << "Avg time/swap : " << (swap_cnt > 0 ? now_time / swap_cnt : 0.0) << " ms" << endl; cerr << "Best Score : " << best_result.true_score << " (" << best_result.score << ")" << endl; cerr << "--- Final Scores by Temp ---" << endl; #pragma omp parallel for schedule(static) for (int i = 0; i < NUM_REPLICAS; ++i) { record_scores[i] = states[rep_idx[i]].get_true_score(); } for (int i = 0; i < NUM_REPLICAS; ++i) { cerr << " Temp[" << i << "] (" << temps[i] << ") : " << record_scores[i] << endl; } } return best_result; } } // namespace sa // 最小化の焼きなまし namespace sa { void sa_init() { titan23::Random sarnd; } /// @brief sa_run に渡す状態の雛形 / TODO の箇所を問題に合わせて書く class State { public: titan23::Random sarnd; using ScoreType = double; // TODO // TODO /// @brief 開始温度と終了温度 struct Param { double start_temp, end_temp; Param() : start_temp(1e2), end_temp(1e0) {} }; inline static Param param; /// @brief 直前の遷移の情報 / type は遷移の種類で [0, TYPE_CNT) struct Changed { int TYPE_CNT = 1; int type; int i, j; int c; Changed() {} } changed; // TODO /// @brief 最良解として保存する情報 struct Result { ScoreType score, true_score; array, N> S; Result() {} Result(ScoreType s, ScoreType ts, array, N> S) : score(s), true_score(ts), S(S) {} void print(ostream &os = cout) const { rep(i, N) { rep(j, N) { os << S[i][j]; } os << "\n"; } } }; bool is_valid; ScoreType score; State() {} // ========================= array, N> S; // TODO /// @brief seed で乱数と状態を初期化する void init(uint32_t seed) { sarnd.set_seed(seed); score = 0; rep(i, N) rep(j, N) S[i][j] = 0; // modify(0, 0, 0); // modify(0, 0, 0); // modify(0, 0, 0); // modify(0, 0, 0); // rep(i, N) { // rep(j, N) { // cout << S[i][j]; // } // cout << "\n"; // } calc_score(); // cerr << "Score = " << score << endl; // exit(0); } void reset_is_valid() { is_valid = true; } ScoreType get_score() const { return score; } ScoreType get_true_score() const { return score; } array B; void calc_score() { const int LEFT = 2; const int RIGHT = 3; const int UP = 1; const int DOWN = 0; /// S[i][j]にいて、dから入ってきた auto conv = [&] (int i, int j, int d) -> tuple { assert(isrange(i, j)); // cerr << "S[i][j] = " << S[i][j] << " | " << "(" << i << ", " << j << ", " << d << ")" << endl; if (S[i][j] == 0) { if (d == DOWN) { // down return {i-1, j, d}; } else if (d == UP) { // up return {i+1, j, d}; } else if (d == LEFT) { // left return {i, j+1, d}; } else { // right return {i, j-1, d}; } } if (S[i][j] == 1) { if (d == 0) { // down return {i, j+1, LEFT}; } else if (d == 1) { // up return {i, j-1, RIGHT}; } else if (d == 2) { // left return {i-1, j, DOWN}; } else { // right return {i+1, j, UP}; } } if (S[i][j] == 2) { if (d == 0) { // down return {i, j-1, RIGHT}; } else if (d == 1) { // up return {i, j+1, LEFT}; } else if (d == 2) { // left return {i+1, j, UP}; } else { // right return {i-1, j, DOWN}; } } assert(false); }; rep(i, M) { // cerr << i << " / " << M << endl; int d = -1; int now_i = -1, now_j = -1; if (i < N) { // 上辺から入る now_i = 0; now_j = i; d = UP; } else if (i < 2*N) { // 右辺から入る now_i = i - N; now_j = N - 1; d = RIGHT; } else if (i < 3*N) { // 下辺から入る now_i = N - 1; now_j = 3*N - 1 - i; d = DOWN; } else { // 左辺から入る now_i = 4*N - 1 - i; now_j = 0; d = LEFT; } int si = now_i, sj = now_j; while (isrange(now_i, now_j)) { // cerr << si << ", " << sj << " -> " << now_i << ", " << now_j << endl; tie(now_i, now_j, d) = conv(now_i, now_j, d); } int idx = -1; // cerr << si << ", " << sj << " -> " << now_i << ", " << now_j << endl; if (now_i == -1) { // 上辺に出た idx = now_j; } else if (now_j == N) { // 右辺に出た idx = N + now_i; } else if (now_i == N) { // 下辺に出た idx = 3*N - 1 - now_j; } else if (now_j == -1) { // 左辺に出た idx = 4*N - 1 - now_i; } assert(0 <= idx && idx < M); B[idx] = A[i]; assert(0 <= idx < M); // cerr << "i=" << i << endl; // cerr << "idx=" << idx << endl; // cerr << "A[i]=" << A[i] << endl; B[idx] = A[i]; } // cerr << B << endl; // rep(i, M) assert(B[i] != -1); int s = 0; rep(i, M) for (int j = i+1; j < M; ++j) { if (i < j && B[i] > B[j]) s++; } // cerr << "tentou = " << s << endl; // s = M*(M-1)/2 - s; score = s; } // TODO /// @brief 近傍へ遷移し、score を更新する / threshold を超えたら必ず棄却され、等しければ遷移する /// is_valid を false にすると必ず棄却され、rollback は呼ばれる / progress は進行度で 0.0 から 1.0 void modify(const int64_t iter, const ScoreType threshold, const double progress) { changed.type = 0; int i = sarnd.randrange(N); int j = sarnd.randrange(N); int c = sarnd.randrange(10); if (c >= 3) c = 0; if (c == S[i][j]) { is_valid = false; return; } changed.i = i; changed.j = j; changed.c = S[i][j]; S[i][j] = c; calc_score(); } /// @brief modify の前の状態に戻す / score はライブラリが元の値に上書きするので復元しなくてよい void rollback() { if (!is_valid) return; S[changed.i][changed.j] = changed.c; } // TODO /// @brief 遷移を確定する / 遅延評価にした場合は、盤面への書き込みをここで確定させる void advance() {} // TODO /// @brief 現在の解を Result で返す Result get_result() const { return {get_score(), get_true_score(), S}; } }; } // namespace sa void solve() { sa::State::Result result = sa::sa_run(19000, 23, true); result.print(); } int main() { ios::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(3); cerr << fixed << setprecision(3); input(); solve(); return 0; }