結果
| 問題 | No.5026 Spectrum Router |
| コンテスト | |
| ユーザー |
taigatappuri
|
| 提出日時 | 2026-11-23 22:59:52 |
| 言語 | C++23(gcc16) (gcc 16.2.0 + boost 1.92.0 + ACL) |
| 結果 |
AC
不安定
|
| 実行時間 | 1,913 ms / 2,000 ms |
| + 913µs | |
| コード長 | 25,629 bytes |
| 記録 | |
| コンパイル時間 | 3,735 ms |
| コンパイル使用メモリ | 376,128 KB |
| 実行使用メモリ | 6,400 KB |
| スコア | 1,425,023 |
| 最終ジャッジ日時 | 2026-11-23 23:14:19 |
| 合計ジャッジ時間 | 106,651 ms |
|
ジャッジサーバーID (参考情報) |
judge2_0 / judge1_0 |
| 純コード判定しない問題か言語 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 50 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using namespace chrono;
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using Graph = vector<vector<long long>>;
#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 <class T>
bool chmax(T &a, const T &b)
{
if (a < b)
{
a = b;
return true;
}
return false;
}
template <class T>
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 <class T>
istream &operator>>(istream &s, vector<T> &v)
{
for (auto &e : v)
s >> e;
return s;
}
template <class T>
ostream &operator<<(ostream &s, const vector<T> &v)
{
for (auto &e : v)
s << e << ' ';
return s;
}
template <class T, class U>
ostream &operator<<(ostream &s, const pair<T, U> &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<chrono::milliseconds>(end_time - start_time).count();
}
template <typename T>
std::string debug_format(const T &value);
template <typename T, typename U>
std::string debug_format(const std::pair<T, U> &value)
{
return "(" + debug_format(value.first) + ", " + debug_format(value.second) + ")";
}
template <typename T>
std::string debug_format(const std::vector<T> &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 <typename T>
std::string debug_format(const T &value)
{
std::ostringstream stream;
stream << value;
return stream.str();
}
template <typename... T>
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<Profile *> &profiles()
{
static std::vector<Profile *> items;
return items;
}
inline Profile::Profile(const char *n, uint64_t k)
: name(n), every(std::max<uint64_t>(1, k))
{
profiles().push_back(this);
}
// 任意のカウンタ
struct Counter
{
const char *name;
uint64_t value = 0;
explicit Counter(const char *n);
};
inline std::vector<Counter *> &counters()
{
static std::vector<Counter *> 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<double, std::milli>(
Clock::now() - started)
.count();
++p.samples;
}
};
// 結果出力
inline void report()
{
using namespace std;
double elapsed = chrono::duration<double, milli>(
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<string, uint64_t> 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 <class T>
T &random_choice(vector<T> &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 <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <utility>
#include <vector>
template <int Bits, class T, class Key>
void stable_radix_sort(std::vector<T> &values, Key &&key)
{
static_assert(1 <= Bits && Bits <= 16);
constexpr unsigned buckets = 1U << Bits, mask = buckets - 1;
using K = std::remove_cvref_t<decltype(key(std::declval<const T &>()))>;
static_assert(std::is_integral_v<K> && std::is_unsigned_v<K> && 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<T> scratch(values.size());
if constexpr (Bits == 11 && sizeof(K) <= 4)
{
if (values.size() <= UINT32_MAX && (varying & mask) && ((varying >> 11) & mask) && (varying >> 22))
{
std::array<std::array<std::uint32_t, buckets>, 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::size_t, buckets>, std::vector<std::size_t>>;
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<std::uint64_t>(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<std::uint64_t>(key(value)) >> shift) & mask]++] = std::move(value);
values.swap(scratch);
}
}
template <class T, class Key>
void stable_radix_sort(std::vector<T> &values, Key key)
{
stable_radix_sort<8>(values, std::move(key));
}
namespace radix_sort_detail
{
template <int Bits = 8, class T, class Key>
void sort_by_key(std::vector<T> &values, Key key)
{
using K = std::remove_cvref_t<decltype(key(std::declval<const T &>()))>;
if constexpr (std::is_integral_v<K> && !std::is_same_v<K, bool> && sizeof(K) <= 8 && std::is_default_constructible_v<T>)
{
using U = std::make_unsigned_t<K>;
constexpr U sign = std::is_signed_v<K> ? U(1) << (sizeof(K) * 8 - 1) : U(0);
stable_radix_sort<Bits>(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 <cassert>
#include <concepts>
#line 10 "sequence/inversion_count.hpp"
#include <functional>
#include <limits>
#include <ranges>
#line 15 "sequence/inversion_count.hpp"
template <class Range, class Compare = std::less<>>
requires std::ranges::random_access_range<const Range> && std::ranges::sized_range<const Range> &&
requires(Compare &compare, std::ranges::iterator_t<const Range> 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<int>::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<std::int64_t>(run++);
}
if (reversed == n)
return static_cast<std::int64_t>(n) * (n - 1) / 2 - equal_pairs;
using T = std::ranges::range_value_t<const Range>;
constexpr bool cached = std::is_trivially_copyable_v<T> && sizeof(T) <= 16 &&
std::is_default_constructible_v<T> && std::is_copy_constructible_v<T> &&
std::is_copy_assignable_v<T> && !std::is_same_v<T, bool>;
using Stored = std::conditional_t<cached, T, int>;
std::vector<Stored> 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<int>(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<std::int64_t>(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<std::int64_t>(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<std::int64_t>(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 <class A, class B>
requires std::ranges::random_access_range<const A> && std::ranges::sized_range<const A> &&
std::ranges::random_access_range<const B> && std::ranges::sized_range<const B> &&
std::same_as<std::ranges::range_value_t<const A>, std::ranges::range_value_t<const B>> &&
std::integral<std::ranges::range_value_t<const A>> && (sizeof(std::ranges::range_value_t<const A>) <= 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<int>::max()));
if (std::ranges::equal(a, b))
return 0;
using T = std::ranges::range_value_t<const A>;
using U = std::make_unsigned_t<std::conditional_t<std::is_same_v<T, bool>, unsigned char, T>>;
const int n = static_cast<int>(std::ranges::size(a));
auto sorted_positions = [](auto first, int n)
{
std::vector<std::pair<U, int>> 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<int> 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<int> 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<string> S;
vector<int> 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<int> calc_B()
{
vector<int> 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()
{
double start_temp = 1.5;
double end_temp = 0.15;
const double log_start_temp = log(start_temp);
const double log_end_temp = log(end_temp);
int TL = 1950;
int time = get_time_global();
best = current;
while(time <= TL)
{
time = get_time_global();
double progress = (double)time / (double)TL;
double temp = exp((1.0 - progress) * log_start_temp + progress * log_end_temp);
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<int> new_B = current.calc_B();
int next_score = inversion_count(new_B);
int delta = next_score - current.score;
if (delta > 0 && rand01() >= exp(-static_cast<double>(delta) / temp))
{
mirror = before_mirror;
continue;
}
current.B = move(new_B);
current.score = next_score;
if (current.score < best.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
めちゃくちゃ上振れますように
22:35
時間もないが、焼きなまし。
22:40
WSLが突然停止...。裏で回してたいろいろな処理が悪さしてそう
急遽 AtCoderのコードテストで書き始めることに...
22:45
WSL復旧。
22:59
ラスサブ。温度調整のみ
*/
taigatappuri