結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー prussian_coder
提出日時 2026-11-10 22:03:32
言語 C++23(gcc16)
(gcc 16.2.0 + boost 1.92.0 + ACL)
コンパイル:
g++-16 -O2 -fplugin=/usr/lib/yukicoder/noavx512-gcc16.so -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 1,792 ms / 2,000 ms
+ 921µs
コード長 15,485 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,134 ms
コンパイル使用メモリ 370,480 KB
実行使用メモリ 9,868 KB
スコア 1,558,945
最終ジャッジ日時 2026-11-23 20:40:52
合計ジャッジ時間 98,691 ms
ジャッジサーバーID
(参考情報)
judge5_0 / judge4_0
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

// Step 9: 反射鏡ではなく「ポートのペア」を焼きなましで探し、最後に鏡の配置を組み立てる
//
// 【1. ペアの問題に言い換える】
// 光は逆向きにも同じ経路を通るので、ポート p から入った光がポート q に届くなら、
// q から入った光は p に届く。つまり盤面は M 個のポートを 2 個ずつ M/2 組のペアに分ける。
// ペアの相手を partner[p] とすると B[q] = A[partner[q]] なので、スコアはペアの組み方だけで決まる。
// そこで反射鏡ではなく、ペアの組み方を直接焼きなましで探す。
//
// 【2. どんなペアなら反射鏡で実現できるか】
// マスを頂点、隣り合うマスの境界とポートを辺とするグラフを考えると、光の経路は辺を共有しないパスになる。
// どのマスでも 4 辺の 2 組への分け方(3 通り)は状態 0, 1, 2 のどれかで選べるので、
// 「ペアごとに辺を共有しないパスを引けるか」が実現可能性の条件になる。
// 端点がすべて外周にあるので、Okamura–Seymour の定理より次の条件と同値になる:
//   盤面を 2 つに分けるどの切断線についても、切断線をまたぐペアの数 ≤ 切断線が横切る辺の数
// この盤面では、上辺の位置 t と下辺の位置 b を結ぶ切断線(と、左辺と右辺を結ぶもの)だけ調べればよく、
// 横切る辺の数は N + |t - b| になる。t, b は 1〜N-1 なので切断線は 2(N-1)^2 本ある。
// なお、またぐペアの数と N + |t - b| の偶奇は常に一致するので、余裕は常に偶数になる。
//
// 【3. 焼きなまし】
// 近傍は、2 組のペア (x0, y0), (x1, y1) を (x0, y1), (x1, y0) に組み替える操作。
// 切断線ごとに余裕(横切る辺の数 − またぐペアの数)を持っておき、
// 余裕のない切断線をまたぐペアが増える変更は採用しない。
//
// 【4. 反射鏡の配置を組み立てる】
// 最良のペアについて、Wagner–Weihe のアルゴリズムで実際の経路を引き、各マスの状態を決める。
//   D. Wagner and K. Weihe, "A linear-time algorithm for edge-disjoint paths in planar graphs",
//   Combinatorica 15(1), 135-150 (1995).
#include <bits/stdc++.h>
using namespace std;

int N, M;
vector<int> A;        // A[p] = ポート p から入る光の番号
vector<int> partner;  // partner[p] = ポート p とペアになるポート
vector<int> B;        // B[q] = ポート q で受信する光の番号 = A[partner[q]]

mt19937 rng(0);
uniform_real_distribution<double> uniform01(0.0, 1.0);
auto start_time = chrono::steady_clock::now();
double elapsed() {
    return chrono::duration<double>(chrono::steady_clock::now() - start_time).count();
}

// ポート p が接するマス (r, c) と、そのマスのどの辺に付いているか(0=上, 1=右, 2=下, 3=左)
void port_cell(int p, int& r, int& c, int& side) {
    if (p < N)          { r = 0;             c = p;             side = 0; }
    else if (p < 2 * N) { r = p - N;         c = N - 1;         side = 1; }
    else if (p < 3 * N) { r = N - 1;         c = 3 * N - 1 - p; side = 2; }
    else                { r = 4 * N - 1 - p; c = 0;             side = 3; }
}

// ======================================================================
// 切断線の条件
// ======================================================================

// 切断線ごとの情報を 64 本ずつ uint64_t のビットにまとめて持つ
const int MAX_WORDS = (2 * 63 * 63 + 63) / 64;  // N = 64 のとき
using CutBits = array<uint64_t, MAX_WORDS>;

int num_words;
vector<CutBits> first_side;  // first_side[p] のビット id: ポート p が切断線 id の左側(上側)にあるか
vector<int> capacity;        // capacity[id] = 切断線 id が横切る辺の数
vector<int> slack;           // slack[id] = (容量 − またぐペアの数) / 2
CutBits tight;               // 余裕が 0 の切断線

// ポート p が切断線の左側(上側)にあるか
// axis = 0: 上辺の位置 t と下辺の位置 b を結ぶ縦の切断線
// axis = 1: 左辺の位置 t と右辺の位置 b を結ぶ横の切断線
bool on_first_side(int p, int axis, int t, int b) {
    int r, c, side;
    port_cell(p, r, c, side);
    if (axis == 0) {
        if (side == 0) return c < t;
        if (side == 2) return c < b;
        return side == 3;
    } else {
        if (side == 3) return r < t;
        if (side == 1) return r < b;
        return side == 0;
    }
}

bool get_bit(const CutBits& bits, int id) { return bits[id / 64] >> (id % 64) & 1; }
void set_bit(CutBits& bits, int id, bool value) {
    if (value) bits[id / 64] |= 1ULL << (id % 64);
    else bits[id / 64] &= ~(1ULL << (id % 64));
}

void init_cuts() {
    first_side.assign(M, CutBits{});
    capacity.clear();
    for (int axis = 0; axis < 2; axis++)
        for (int t = 1; t < N; t++)
            for (int b = 1; b < N; b++) {
                int id = capacity.size();
                capacity.push_back(N + abs(t - b));
                for (int p = 0; p < M; p++) set_bit(first_side[p], id, on_first_side(p, axis, t, b));
            }
    num_words = (capacity.size() + 63) / 64;

    // 今のペアについて、各切断線の余裕を数える
    slack.assign(capacity.size(), 0);
    tight = CutBits{};
    for (int id = 0; id < (int)capacity.size(); id++) {
        int crossing = 0;
        for (int p = 0; p < M; p++)
            if (p < partner[p] && get_bit(first_side[p], id) != get_bit(first_side[partner[p]], id)) crossing++;
        slack[id] = (capacity[id] - crossing) / 2;
        set_bit(tight, id, slack[id] == 0);
    }
}

// 「ポート u と v がペアなら、切断線をまたぐか」をビットごとに表したもの(w 番目の 64 本分)
uint64_t crosses(int u, int v, int w) { return first_side[u][w] ^ first_side[v][w]; }

// ペア (x0, y0), (x1, y1) を (x0, y1), (x1, y0) に組み替えるとき、切断線の条件を満たすか調べる。
// apply = true なら、余裕を更新する。
//
// 1 本の切断線について、4 つのポートのうち片側にあるものの数は組み替えで変わらないので、
// またぐペアの数は 0 → 2, 2 → 0 と変わるか、変わらないかのどれか。
bool check_cuts(int x0, int y0, int x1, int y1, bool apply) {
    for (int w = 0; w < num_words; w++) {
        uint64_t old_both = crosses(x0, y0, w) & crosses(x1, y1, w);  // 組み替え前に 2 組ともまたぐ
        uint64_t new_both = crosses(x0, y1, w) & crosses(x1, y0, w);  // 組み替え後に 2 組ともまたぐ
        uint64_t increase = new_both & ~old_both;
        uint64_t decrease = old_both & ~new_both;

        if (!apply) {
            if (increase & tight[w]) return false;  // 余裕のない切断線をまたぐペアが増える
            continue;
        }
        // 立っているビットだけを順に見る(__builtin_ctzll は最下位の 1 の位置)
        for (uint64_t changed = increase | decrease; changed; changed &= changed - 1) {
            int bit = __builtin_ctzll(changed), id = w * 64 + bit;
            slack[id] += (decrease >> bit & 1) ? 1 : -1;
            set_bit(tight, id, slack[id] == 0);
        }
    }
    return true;
}

// ======================================================================
// 転倒数
// ======================================================================

int count_inversions() {
    int inv = 0;
    for (int i = 0; i < M; i++)
        for (int j = i + 1; j < M; j++)
            if (B[i] > B[j]) inv++;
    return inv;
}

// B[i] と B[j] を入れ替え、転倒数の変化量を返す。
// 変わるのは i, j 自身の組と、間にある値のうち 2 つの値の間に入るものとの組だけ。
int swap_B(int i, int j) {
    if (i > j) swap(i, j);
    int lo = min(B[i], B[j]), hi = max(B[i], B[j]), between = 0;
    for (int t = i + 1; t < j; t++)
        if (lo < B[t] && B[t] < hi) between++;
    int delta = (B[i] < B[j] ? 1 : -1) * (1 + 2 * between);
    swap(B[i], B[j]);
    return delta;
}

// 位置 pos[0..n-1] の値を values[0..n-1] に変え、転倒数の変化量を返す。
// values は、変更前のこれらの位置の値の並べ替えであること。
int set_B(const int* pos, const int* values, int n) {
    int delta = 0;
    for (int i = 0; i < n; i++) {
        if (B[pos[i]] == values[i]) continue;
        int j = i + 1;
        while (B[pos[j]] != values[i]) j++;
        delta += swap_B(pos[i], pos[j]);
    }
    return delta;
}

// ======================================================================
// 反射鏡の配置を組み立てる(Wagner–Weihe のアルゴリズム)
// ======================================================================
//
// マス cell の辺 side を「半辺」h = 4 * cell + side で表す。
// next_half[h] は、境界をはさんだ隣のマスの半辺。外周ならポート p を -1 - p で表す。
// 状態 s のマスでは、半辺 h と h ^ CONNECT[s] がつながる
// (0: 上と下・左と右, 1 '/': 上と左・右と下, 2 '\': 上と右・下と左)。
const int CONNECT[3] = {2, 3, 1};
vector<int> next_half;
vector<int> entrance_half;  // entrance_half[p] = ポート p に接する半辺

void init_half_edges() {
    const int DR[4] = {-1, 0, 1, 0}, DC[4] = {0, 1, 0, -1};
    next_half.assign(4 * N * N, 0);
    entrance_half.assign(M, 0);
    for (int r = 0; r < N; r++)
        for (int c = 0; c < N; c++)
            for (int side = 0; side < 4; side++) {
                int h = 4 * (r * N + c) + side;
                int r2 = r + DR[side], c2 = c + DC[side];
                if (0 <= r2 && r2 < N && 0 <= c2 && c2 < N) next_half[h] = 4 * (r2 * N + c2) + (side ^ 2);
            }
    for (int p = 0; p < M; p++) {
        int r, c, side;
        port_cell(p, r, c, side);
        entrance_half[p] = 4 * (r * N + c) + side;
        next_half[entrance_half[p]] = -1 - p;
    }
}

// 盤面 board でポート p から入った光が出ていくポート
int trace(const vector<int>& board, int p) {
    int h = entrance_half[p];
    while (h >= 0) h = next_half[h ^ CONNECT[board[h / 4]]];
    return -1 - h;
}

// マスに半辺 h から入ったとき、出ていく半辺の候補を優先順に返す。
// 入った辺から反時計回りに見ていく(進行方向から見て右、直進、左の順)。
array<int, 3> exits_in_order(int h) {
    int cell = h / 4, side = h % 4;
    return {4 * cell + (side + 3) % 4, 4 * cell + (side + 2) % 4, 4 * cell + (side + 1) % 4};
}

// partner のペアを実現する盤面を作る。作れなければ空の vector を返す。
vector<int> build_board() {
    vector<int> direction(4 * N * N, 0);  // 半辺の向き: +1 = マスから出る, -1 = マスに入る
    vector<int> stack, order;

    // 1 段目: ポートを番号の大きい順に見て、括弧の対応のように交差しないペアを作り、
    // それぞれ「右手を壁につけて進む」ように経路を引いて、使った辺に向きを付ける。
    for (int t = M - 1; t >= 0; t--) {
        if (partner[t] < t) { stack.push_back(t); continue; }
        int s = stack.back();
        stack.pop_back();
        order.push_back(t);

        int h = entrance_half[s];
        direction[h] = -1;
        while (h >= 0) {
            int out = -1;
            for (int e : exits_in_order(h))
                if (direction[e] == 0) { out = e; break; }
            if (out == -1) return {};
            direction[out] = 1;
            h = next_half[out];
            if (h >= 0) direction[h] = -1;
        }
        if (-1 - h != t) return {};
    }

    // 2 段目: 本当のペアについて、1 段目で付けた向きに沿って、まだ使っていない辺だけを通る経路を引く。
    // 経路が通るマスでは、入った辺と出た辺がつながるように状態を決める。
    vector<int> board(N * N, 0);
    vector<bool> used(4 * N * N, false);
    for (int t : order) {
        int h = entrance_half[partner[t]];
        used[h] = true;
        while (h >= 0) {
            int out = -1;
            for (int e : exits_in_order(h))
                if (direction[e] == 1 && !used[e]) { out = e; break; }
            if (out == -1) return {};
            int key = h ^ out;
            board[h / 4] = key == 2 ? 0 : key == 3 ? 1 : 2;
            used[out] = true;
            h = next_half[out];
            if (h >= 0) used[h] = true;
        }
        if (-1 - h != t) return {};
    }

    // 念のため、本当にペアが実現できているか確かめる
    for (int p = 0; p < M; p++)
        if (trace(board, p) != partner[p]) return {};
    return board;
}

// ======================================================================
// メイン
// ======================================================================

int main() {
    cin >> N;
    M = 4 * N;
    A.resize(M);
    for (int& a : A) cin >> a;

    // 初期解: 反射鏡を置かない盤面のペア
    init_half_edges();
    partner.resize(M);
    B.resize(M);
    for (int p = 0; p < M; p++) partner[p] = trace(vector<int>(N * N, 0), p);
    for (int q = 0; q < M; q++) B[q] = A[partner[q]];
    init_cuts();

    int score = M * (M - 1) / 2 - count_inversions();
    int best_score = score;
    vector<int> best_partner = partner;

    const double TIME_LIMIT = 1.8, START_TEMP = 30.0, END_TEMP = 0.1;
    double temp = START_TEMP;
    long long trials = 0;
    while (true) {
        if (trials % 256 == 0) {
            double t = elapsed() / TIME_LIMIT;
            if (t >= 1.0) break;
            temp = START_TEMP * pow(END_TEMP / START_TEMP, t);
        }
        trials++;

        // 2 組のペア (x0, y0), (x1, y1) を選び、(x0, y1), (x1, y0) に組み替える
        int x0 = rng() % M, y0 = partner[x0];
        int y1 = rng() % M, x1 = partner[y1];
        if (y1 == x0 || y1 == y0) continue;  // 同じペアを選んだ

        // 組み替え後の受信番号: B[x0] = A[y1], B[y1] = A[x0], B[x1] = A[y0], B[y0] = A[x1]
        int pos[4] = {x0, y1, x1, y0};
        int new_values[4] = {A[y1], A[x0], A[y0], A[x1]};
        int old_values[4] = {B[x0], B[y1], B[x1], B[y0]};
        int delta = -set_B(pos, new_values, 4);  // スコアの変化量

        // 焼きなましの判定に通ったものだけ、切断線の条件を調べる
        bool accept = delta >= 0 || uniform01(rng) < exp(delta / temp);
        if (accept) accept = check_cuts(x0, y0, x1, y1, false);
        if (!accept) {
            set_B(pos, old_values, 4);
            continue;
        }

        check_cuts(x0, y0, x1, y1, true);
        partner[x0] = y1; partner[y1] = x0;
        partner[x1] = y0; partner[y0] = x1;
        score += delta;
        if (score > best_score) {
            best_score = score;
            best_partner = partner;
        }
    }

    partner = best_partner;
    vector<int> board = build_board();
    if (board.empty()) {
        cerr << "failed to build the board\n";
        board.assign(N * N, 0);
    }
    for (int r = 0; r < N; r++) {
        for (int c = 0; c < N; c++) cout << board[r * N + c];
        cout << '\n';
    }
    cerr << "trials = " << trials << ", score = " << best_score << '\n';
}
0