結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー prussian_coder
提出日時 2026-11-22 16:59:27
言語 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,991 ms / 2,000 ms
+ 528µs
コード長 8,137 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,828 ms
コンパイル使用メモリ 370,360 KB
実行使用メモリ 9,904 KB
スコア 1,498,363
最終ジャッジ日時 2026-11-23 20:47:13
合計ジャッジ時間 109,397 ms
ジャッジサーバーID
(参考情報)
judge5_0 / judge4_0
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

// main.py の C++ 移植: 鏡の配置を焼きなまし法で改善する解法。
#include <bits/stdc++.h>
using namespace std;

// 方向は下・左・上・右の順。盤面外周の入口番号もこの順に対応する。
const int DR[4] = {1, 0, -1, 0};
const int DC[4] = {0, -1, 0, 1};
const char OUTPUT_CODES[4] = {'0', '1', '?', '2'};  // 0,1,3 のみ使用

const double TIME_LIMIT = 2.0;
const double START_TEMPERATURE = 300.0;
const double END_TEMPERATURE = 10.0;

mt19937 rng(random_device{}());
uniform_real_distribution<double> uniform01(0.0, 1.0);

auto start_clock = chrono::steady_clock::now();
double elapsed() {
    return chrono::duration<double>(chrono::steady_clock::now() - start_clock).count();
}

struct BinaryIndexedTree {
    int size;
    vector<int> bit;

    explicit BinaryIndexedTree(int n) : size(n), bit(n + 1, 0) {}

    int sum(int i) const {
        int res = 0;
        while (i > 0) {
            res += bit[i];
            i -= i & -i;
        }
        return res;
    }

    void add(int i, int x) {
        while (i <= size) {
            bit[i] += x;
            i += i & -i;
        }
    }
};

int inversion_num(const vector<int>& ls, int n) {
    int ans = 0;
    BinaryIndexedTree bit(n);
    for (int i = 0; i < (int)ls.size(); i++) {
        ans += i - bit.sum(ls[i]);
        bit.add(ls[i] + 1, 1);
    }
    return ans;
}

struct Solver {
    int n;
    int width;  // 外周の入口・出口を含む盤面幅
    vector<int> ball_values;
    vector<int> board;
    vector<int> best_board;
    vector<int> entrance_cells;
    vector<int> entrance_at;  // cell -> entrance index, なければ -1
    vector<int> final_balls;  // 出口に届いたボールの値
    // incoming[cell][direction]: その方向からセルに入るボールの番号
    vector<array<int, 4>> incoming;

    Solver(int n_, const vector<int>& ball_values_)
        : n(n_), width(n_ + 2), ball_values(ball_values_) {
        int cells = width * width;
        board.assign(cells, 0);
        entrance_at.assign(cells, -1);
        incoming.assign(cells, {-1, -1, -1, -1});
        final_balls.assign(4 * n, -1);
        entrance_cells = make_entrance_cells();
        for (int i = 0; i < (int)entrance_cells.size(); i++) {
            entrance_at[entrance_cells[i]] = i;
        }
        for (int ball_id = 0; ball_id < 4 * n; ball_id++) {
            trace_and_record(ball_id);
        }
        best_board = board;
    }

    int cell(int row, int col) const { return row * width + col; }

    int move(int c, int direction) const {
        int row = c / width;
        int col = c % width;
        return cell(row + DR[direction], col + DC[direction]);
    }

    vector<int> make_entrance_cells() const {
        // 入口番号 0..4N-1 に対応する外周セルを作る。
        vector<int> cells(4 * n, -1);
        for (int entrance = 0; entrance < 4 * n; entrance++) {
            int offset = entrance % n;
            if (entrance < n) {  // 上辺: 左から右
                cells[entrance] = cell(0, offset + 1);
            } else if (entrance < 2 * n) {  // 右辺: 上から下
                cells[entrance] = cell(offset + 1, width - 1);
            } else if (entrance < 3 * n) {  // 下辺: 右から左
                cells[entrance] = cell(width - 1, width - 2 - offset);
            } else {  // 左辺: 下から上
                cells[entrance] = cell(width - 2 - offset, 0);
            }
        }
        return cells;
    }

    static int reflect(int direction, int mirror) { return direction ^ mirror; }

    void erase_balls(int ball_id) {
        int c = entrance_cells[ball_id];
        int direction = ball_id / n;
        while (true) {
            c = move(c, direction);
            if (entrance_at[c] != -1) {
                int entrance_id = entrance_at[c];
                final_balls[entrance_id] = -1;
                return;
            }
            incoming[c][direction] = -1;
            direction = reflect(direction, board[c]);
        }
    }

    void trace_and_record(int ball_id) {
        // ボールの経路をたどり、通過セルの入射方向を記録する。
        int c = entrance_cells[ball_id];
        int direction = ball_id / n;
        while (true) {
            c = move(c, direction);
            if (entrance_at[c] != -1) {
                int entrance_id = entrance_at[c];
                final_balls[entrance_id] = ball_values[ball_id];
                return;
            }
            incoming[c][direction] = ball_id;
            direction = reflect(direction, board[c]);
        }
    }

    int cost_if_mirror(int c, int mirror) const {
        // セルに mirror を置いたときの局所的な評価値を返す。
        const auto& inc = incoming[c];
        bool has_empty = false;
        for (int d = 0; d < 4; d++) {
            if (inc[d] == -1) {
                has_empty = true;
                break;
            }
        }
        if (has_empty) {
            return mirror == 0 ? 1000 : -1000;
        }
        int cost = 0;
        for (int i = 0; i < 4; i++) {
            int value = ball_values[inc[i]];
            int paired_id = inc[i ^ mirror ^ 2];
            cost += value * paired_id;
        }
        return cost;
    }

    double temperature(double elapsed_sec) const {
        double progress = elapsed_sec / TIME_LIMIT;
        return START_TEMPERATURE * (1.0 - progress) + END_TEMPERATURE * progress;
    }

    bool try_change_mirror(int c) {
        int old_mirror = board[c];
        // Python: random.randint(0, 4) の後、偶数なら 0 に落とす → 0, 1, 3
        int new_mirror = int(rng() % 5);
        if (new_mirror % 2 == 0) new_mirror = 0;
        if (old_mirror == new_mirror) return false;

        int old_cost = cost_if_mirror(c, old_mirror);
        int new_cost = cost_if_mirror(c, new_mirror);
        int delta = new_cost - old_cost;
        double temp = temperature(elapsed());

        if (delta > temp * log(uniform01(rng))) {
            vector<int> change_balls;
            change_balls.reserve(4);
            for (int ball : incoming[c]) {
                if (ball != -1) change_balls.push_back(ball);
            }
            for (int ball_id : change_balls) erase_balls(ball_id);
            board[c] = new_mirror;
            for (int ball_id : change_balls) trace_and_record(ball_id);
            return true;
        }
        return false;
    }

    int accurately_calculate_score() const {
        int m = n * 4;
        int inversion = inversion_num(final_balls, m);
        return m * (m - 1) / 2 - inversion;
    }

    void optimize() {
        // 時間制限まで鏡の変更を試し、最良盤面を保持する。
        long long attempts = 0;
        long long accepted = 0;
        int best_score = accurately_calculate_score();
        best_board = board;
        while (elapsed() < TIME_LIMIT) {
            attempts++;
            int row = int(rng() % n);
            int col = int(rng() % n);
            int c = cell(row + 1, col + 1);
            if (try_change_mirror(c)) {
                accepted++;
                int score = accurately_calculate_score();
                if (score > best_score) {
                    best_board = board;
                    best_score = score;
                }
            }
        }
        cerr << attempts << ' ' << accepted << '\n';
        cerr << best_score << '\n';
    }

    void write_answer() const {
        // 盤面内の鏡だけを標準出力に書き出す。
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                int c = cell(row + 1, col + 1);
                cout << OUTPUT_CODES[best_board[c]];
            }
            cout << '\n';
        }
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    start_clock = chrono::steady_clock::now();

    int n;
    cin >> n;
    vector<int> ball_values(4 * n);
    for (int& v : ball_values) cin >> v;

    Solver solver(n, ball_values);
    solver.optimize();
    solver.write_answer();
    return 0;
}
0