結果
問題 |
No.1284 Flip Game
|
ユーザー |
![]() |
提出日時 | 2025-04-16 01:12:22 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 1,144 ms / 2,000 ms |
コード長 | 2,350 bytes |
コンパイル時間 | 399 ms |
コンパイル使用メモリ | 81,240 KB |
実行使用メモリ | 131,040 KB |
最終ジャッジ日時 | 2025-04-16 01:14:08 |
合計ジャッジ時間 | 8,997 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 28 |
ソースコード
import heapq def main(): N = int(input()) c = [list(map(int, input().split())) for _ in range(N)] INF = float('inf') full_mask = (1 << N) - 1 heap = [] dist = dict() for q0 in range(N): initial_mask = 1 << q0 prev = q0 flipped_B = 0 state = (initial_mask, prev, flipped_B) if state not in dist or 0 < dist.get(state, INF): dist[state] = 0 heapq.heappush(heap, (0, initial_mask, prev, flipped_B)) answer = INF while heap: current_cost, mask, prev, flipped_B = heapq.heappop(heap) if current_cost > dist.get((mask, prev, flipped_B), INF): continue for next_q in range(N): if not (mask & (1 << next_q)): cost_step = c[prev][next_q] new_mask_A = mask | (1 << next_q) if new_mask_A == full_mask: if (flipped_B & (1 << prev)): if current_cost + cost_step < answer: answer = current_cost + cost_step continue else: new_mask = new_mask_A ^ (1 << prev) new_flipped_B = flipped_B | (1 << prev) new_prev = next_q new_cost = current_cost + cost_step key = (new_mask, new_prev, new_flipped_B) if new_cost < dist.get(key, INF): dist[key] = new_cost heapq.heappush(heap, (new_cost, new_mask, new_prev, new_flipped_B)) else: if (flipped_B & (1 << prev)) == 0: new_mask = new_mask_A ^ (1 << prev) new_flipped_B = flipped_B | (1 << prev) else: new_mask = new_mask_A new_flipped_B = flipped_B new_prev = next_q new_cost = current_cost + cost_step key = (new_mask, new_prev, new_flipped_B) if new_cost < dist.get(key, INF): dist[key] = new_cost heapq.heappush(heap, (new_cost, new_mask, new_prev, new_flipped_B)) print(answer) if __name__ == "__main__": main()