結果

問題 No.5020 Averaging
ユーザー ra5anchor
提出日時 2025-01-25 12:21:47
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 907 ms / 1,000 ms
コード長 4,597 bytes
コンパイル時間 746 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 78,464 KB
スコア 82,173,312
最終ジャッジ日時 2025-01-25 12:22:36
合計ジャッジ時間 49,124 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #

import random
import math
from time import perf_counter
import sys

try:
    import matplotlib.pyplot as plt
    USE_PLOT = True
except ImportError:
    # matplotlib が無い環境ではグラフ表示をしない
    USE_PLOT = False

class TimeKeeper:
    def __init__(self):
        self.start_time = perf_counter()
    def is_time_over(self, LIMIT):
        return (perf_counter() - self.start_time) >= LIMIT
    def time_now(self):
        return (perf_counter() - self.start_time)

# 定数とグローバル変数
TARGET = 500000000000000000
N = 0
A = []
B = []
Order = []
BestOrder = []

def get_score():
    """
    現在の Order 順に従い V1, V2 を計算し、
    最後に max(|TARGET - V1|, |TARGET - V2|) を返す。
    """
    V1, V2 = A[0], B[0]
    for i in range(N - 1):
        V1 = (V1 + A[Order[i]]) // 2
        V2 = (V2 + B[Order[i]]) // 2
    return max(abs(TARGET - V1), abs(TARGET - V2))

def main():
    global N, A, B, Order, BestOrder

    # 乱数シードを固定
    random.seed(0)

    tk = TimeKeeper()
    LIMIT = 0.85

    # 入力
    N = int(input()) # N=45固定
    A = [0] * N
    B = [0] * N
    for i in range(N):
        A[i], B[i] = map(int, input().split())

    # --- 初期解作成例: (A[i], B[i]) が TARGET に遠い順に並べる ---
    def dist_from_target(i):
        return -1 * max(abs(A[i] - TARGET), abs(B[i] - TARGET))

    candidates = list(range(1, N))
    candidates.sort(key=dist_from_target)
    Order = candidates[:]

    # スコア計算
    current_score = get_score()
    best_score = current_score
    BestOrder = Order[:]

    # --- ログ用リスト ---
    # (iteration, best_score, current_score, elapsed_time) を保存
    score_history = []
    score_history.append((0, best_score, current_score, tk.time_now()))

    # ---- 焼きなましパラメータ ----
    loop = 0
    T0, T1 = 0.2, 0.2
    T = T0

    while True:
        loop += 1
        # 一定ループごとに温度を更新 + タイムオーバー判定
        if loop % 1000 == 0:
            T = T0 + (T1 - T0) * tk.time_now() / LIMIT
            if tk.is_time_over(LIMIT):
                break

            # 1000ループごとにログに追加 (ベストスコアの推移を確認)
            score_history.append((loop, best_score, current_score, tk.time_now()))

        # ランダムスワップ
        idx1 = random.randrange(N - 1)
        idx2 = random.randrange(N - 1)
        Order[idx1], Order[idx2] = Order[idx2], Order[idx1]

        # スコア計算
        cand_score = get_score()
        diff = math.log10(current_score) - math.log10(cand_score)

        # メトロポリス判定
        if random.random() < math.exp(diff / T):
            # 採用
            if best_score > cand_score:
                best_score = cand_score
                BestOrder = Order[:]
            current_score = cand_score
        else:
            # 不採用なら元に戻す
            Order[idx1], Order[idx2] = Order[idx2], Order[idx1]

    # 探索終了後に最終的な値も記録
    score_history.append((loop, best_score, current_score, tk.time_now()))

    # 結果出力 (提出フォーマットに応じて調整)
    ANS = [(1, BestOrder[i] + 1) for i in range(N - 1)]
    print(len(ANS))
    for a in ANS:
        print(a[0], a[1])

    sc = int(2*10**6 - 10**5 * math.log10(best_score + 1))
    print(sc, best_score, loop, file=sys.stderr)

    # ---------------------
    #   ログの可視化
    # ---------------------
    if USE_PLOT:
        # matplotlib が利用できる場合にグラフ化
        loops = [h[0] for h in score_history]
        best_scores = [h[1] for h in score_history]
        curr_scores = [h[2] for h in score_history]
        times = [h[3] for h in score_history]

        fig, ax1 = plt.subplots()
        ax1.set_xlabel('Iteration')
        ax1.set_ylabel('Score (log scale)')
        # ログスケールをとるために log10(スコア+1) で表示
        ax1.plot(loops, [math.log10(bs+1) for bs in best_scores],
                 label='Best Score (log10)', color='blue')
        ax1.plot(loops, [math.log10(cs+1) for cs in curr_scores],
                 label='Current Score (log10)', color='red', alpha=0.5)

        ax1.legend(loc='upper right')
        ax1.set_title('Annealing Score Transition')

        # 時間との関係を見る場合には別の軸を用意しても良い
        # 例: ax2 = ax1.twinx() など

        plt.show()
        # plt.savefig('score_history.png')  # ファイルに保存も可能

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