結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー prussian_coder
提出日時 2026-11-23 20:57:26
言語 PyPy3
(8.0.1 + ACL)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
TLE  
実行時間 -
コード長 6,526 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 100 ms
コンパイル使用メモリ 64,608 KB
実行使用メモリ 90,892 KB
スコア 0
最終ジャッジ日時 2026-11-23 20:59:13
合計ジャッジ時間 106,559 ms
ジャッジサーバーID
(参考情報)
judge6_0 / judge4_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 30 TLE * 20
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

"""鏡の配置を焼きなまし法で改善する解法。"""

import math
import random
import sys
import time


# 方向は下・左・上・右の順。盤面外周の入口番号もこの順に対応する。
DIRECTIONS = ((1, 0), (0, -1), (-1, 0), (0, 1))
OUTPUT_CODES = {0: "0", 1: "1", 3: "2"}
TIME_LIMIT = 1.98
START_TEMPERATURE = 100.0
END_TEMPERATURE = 1.0


class Solver:
    """盤面、各ボールの経路、焼きなまし探索を管理する。"""

    def __init__(self, n: int, ball_values: list[int], start_time: float) -> None:
        self.n = n
        self.width = n + 2  # 外周の入口・出口を含む盤面幅
        self.ball_values = ball_values
        self.start_time = start_time

        self.board = [0] * (self.width * self.width)
        self.entrance_cells = self._make_entrance_cells()
        self.entrance_at = {cell: i for i, cell in enumerate(self.entrance_cells)}

        # incoming[cell][direction] は、その方向からセルに入るボールの番号。
        self.incoming = [[-1] * 4 for _ in range(self.width * self.width)]
        for ball_id in range(4 * n):
            self._trace_and_record(ball_id)

    def _cell(self, row: int, col: int) -> int:
        """外周を含む盤面上の座標を一次元の番号に変換する。"""
        return row * self.width + col

    def _move(self, cell: int, direction: int) -> int:
        row, col = divmod(cell, self.width)
        dr, dc = DIRECTIONS[direction]
        return self._cell(row + dr, col + dc)

    def _make_entrance_cells(self) -> list[int]:
        """入口番号 0..4N-1 に対応する外周セルを作る。"""
        cells = [-1] * (4 * self.n)
        for entrance in range(4 * self.n):
            offset = entrance % self.n
            if entrance < self.n:  # 上辺: 左から右
                cells[entrance] = self._cell(0, offset + 1)
            elif entrance < 2 * self.n:  # 右辺: 上から下
                cells[entrance] = self._cell(offset + 1, self.width - 1)
            elif entrance < 3 * self.n:  # 下辺: 右から左
                cells[entrance] = self._cell(self.width - 1, self.width - 2 - offset)
            else:  # 左辺: 下から上
                cells[entrance] = self._cell(self.width - 2 - offset, 0)
        return cells

    @staticmethod
    def _reflect(direction: int, mirror: int) -> int:
        """鏡に当たった後の進行方向を返す。"""
        return direction ^ mirror

    def _erace_balls(self, ball_id: int) -> None:
        cell = self.entrance_cells[ball_id]
        direction = ball_id // self.n

        while True:
            cell = self._move(cell, direction)
            if cell in self.entrance_at:
                return

            self.incoming[cell][direction] = -1
            direction = self._reflect(direction, self.board[cell])


    def _trace_and_record(self, ball_id: int) -> None:
        """ボールの経路をたどり、通過セルの入射方向を記録する。"""
        cell = self.entrance_cells[ball_id]
        direction = ball_id // self.n

        while True:
            cell = self._move(cell, direction)
            if cell in self.entrance_at:
                return

            self.incoming[cell][direction] = ball_id
            direction = self._reflect(direction, self.board[cell])

    def _cost_if_mirror(self, cell: int, mirror: int) -> int:
        """セルに mirror を置いたときの局所的な評価値を返す。"""
        incoming = self.incoming[cell]
        if -1 in incoming:
            if mirror == 0:
                return 1000
            else:
                return -1000
        ball_values = [self.ball_values[ball_id] for ball_id in incoming]
        paired_balls = [incoming[i ^ mirror ^ 2] for i in range(4)]
        return sum(value * paired_id for value, paired_id in zip(ball_values, paired_balls))

    def _temperature(self, elapsed: float) -> float:
        progress = elapsed / TIME_LIMIT
        return START_TEMPERATURE * (1.0 - progress) + END_TEMPERATURE * progress

    def _try_change_mirror(self, cell: int) -> bool:
        """鏡をランダムに変更する。戻り値は (変更候補, 採用) 。"""
        old_mirror = self.board[cell]
        new_mirror = random.randint(0,4)
		# 鏡なし:/:\ = 3:1:1とすると、不必要に鏡が置かれなくなるので、割とスコアが伸びそう
        if new_mirror % 2 == 0:
            new_mirror = 0
        if old_mirror == new_mirror:
            return False

        old_cost = self._cost_if_mirror(cell, old_mirror)
        new_cost = self._cost_if_mirror(cell, new_mirror)
        delta = new_cost - old_cost
        temperature = self._temperature(time.time() - self.start_time)

        if delta > temperature * math.log(random.random()):
            change_balls = [ball for ball in self.incoming[cell] if ball!=-1]
            for ball_id in change_balls:
                self._erace_balls(ball_id)
            self.board[cell] = new_mirror
            for ball_id in change_balls:
                self._trace_and_record(ball_id)
            return True
        return False

    def optimize(self) -> tuple[int, int]:
        """時間制限まで鏡の変更を試し、試行数と採用数を返す。"""
        attempts = 0
        accepted = 0
        while time.time() - self.start_time < TIME_LIMIT:
            attempts += 1
            row = random.randrange(self.n)
            col = random.randrange(self.n)
            cell = self._cell(row + 1, col + 1)
            was_accepted = self._try_change_mirror(cell)
 
            if was_accepted:
                accepted += 1

        return attempts, accepted

    def write_answer(self) -> None:
        """盤面内の鏡だけを標準出力に書き出す。"""
        for row in range(self.n):
            symbols = []
            for col in range(self.n):
                cell = self._cell(row + 1, col + 1)
                symbols.append(OUTPUT_CODES[self.board[cell]])
            print("".join(symbols))


def read_input() -> tuple[int, list[int]]:
    n = int(sys.stdin.readline())
    ball_values = list(map(int, sys.stdin.readline().split()))
    return n, ball_values


def main() -> None:
    start_time = time.time()
    n, ball_values = read_input()
    solver = Solver(n, ball_values, start_time)
    attempts, accepted = solver.optimize()
    print(f"{attempts} {accepted}", file=sys.stderr)
    solver.write_answer()


if __name__ == "__main__":
    main()
0