結果

問題 No.1284 Flip Game
ユーザー lam6er
提出日時 2025-04-16 01:12:10
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,478 ms / 2,000 ms
コード長 2,005 bytes
コンパイル時間 323 ms
コンパイル使用メモリ 82,132 KB
実行使用メモリ 134,308 KB
最終ジャッジ日時 2025-04-16 01:14:01
合計ジャッジ時間 11,523 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

import heapq

def main():
    import sys
    input = sys.stdin.read().split()
    idx = 0
    N = int(input[idx])
    idx += 1
    c = []
    for _ in range(N):
        row = list(map(int, input[idx:idx+N]))
        c.append(row)
        idx += N
    
    heap = []
    INF = float('inf')
    for s in range(N):
        white_mask = 1 << s
        B_flipped = 0
        previous_p = s
        heapq.heappush(heap, (0, white_mask, B_flipped, previous_p))
    
    distance = {}
    for s in range(N):
        white_mask = 1 << s
        B_flipped = 0
        previous_p = s
        distance_key = (white_mask, B_flipped, previous_p)
        distance[distance_key] = 0
    
    answer = INF
    all_white = (1 << N) - 1
    
    while heap:
        current_cost, white_mask, B_flipped, previous_p = heapq.heappop(heap)
        
        if current_cost > distance.get((white_mask, B_flipped, previous_p), INF):
            continue
        
        for q in range(N):
            if (white_mask & (1 << q)) != 0:
                continue
            
            new_white = white_mask | (1 << q)
            cost_increment = c[previous_p][q]
            new_cost = current_cost + cost_increment
            
            if (B_flipped & (1 << previous_p)):
                new_B = B_flipped
                new_white_after_B = new_white
            else:
                new_B = B_flipped | (1 << previous_p)
                new_white_after_B = new_white & ~ (1 << previous_p)
            
            if new_white_after_B == all_white:
                if (B_flipped & (1 << previous_p)):
                    if new_cost < answer:
                        answer = new_cost
            else:
                key = (new_white_after_B, new_B, q)
                if key not in distance or new_cost < distance.get(key, INF):
                    distance[key] = new_cost
                    heapq.heappush(heap, (new_cost, new_white_after_B, new_B, q))
    
    print(answer)

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