結果
| 問題 |
No.470 Inverse S+T Problem
|
| コンテスト | |
| ユーザー |
maspy
|
| 提出日時 | 2023-05-28 04:30:31 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
AC
|
| 実行時間 | 1,271 ms / 2,000 ms |
| コード長 | 1,729 bytes |
| コンパイル時間 | 204 ms |
| コンパイル使用メモリ | 12,800 KB |
| 実行使用メモリ | 111,236 KB |
| 最終ジャッジ日時 | 2024-12-26 10:55:56 |
| 合計ジャッジ時間 | 34,570 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
| 外部呼び出し有り |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 27 |
ソースコード
#!/usr/bin/env python3.8
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import itertools
import numpy as np
from scipy.sparse.csgraph import connected_components
N = int(readline())
if N > 52:
print('Impossible')
exit()
words = [readline().rstrip().decode() for _ in range(N)]
AB = []
for i, j in itertools.product(range(N), repeat=2):
if i == j:
continue
S = words[i]
T = words[j]
if S[0] == T[0] or S[1:] == T[1:]:
AB.append((2 * i, 2 * j + 1))
if S[-1] == T[-1] or S[:2] == T[:2]:
AB.append((2 * i + 1, 2 * j))
if S[0] == T[-1] or S[1:] == T[:2]:
AB.append((2 * i, 2 * j))
if S[-1] == T[0] or S[:2] == T[1:]:
AB.append((2 * i + 1, 2 * j + 1))
G = np.zeros((N + N, N + N), np.bool_)
for a, b in AB:
G[a, b] = 1
C, comp = connected_components(G, directed=True, connection='strong')
graph = [[] for _ in range(C)]
in_deg = [0] * C
for a, b in AB:
ca = comp[a]
cb = comp[b]
if ca == cb:
continue
graph[ca].append(cb)
in_deg[cb] += 1
order = []
deg_0 = [i for i, x in enumerate(in_deg) if x == 0]
while deg_0:
v = deg_0.pop()
order.append(v)
for w in graph[v]:
in_deg[w] -= 1
if not in_deg[w]:
deg_0.append(w)
rank = [0] * C
for i, x in enumerate(order):
rank[x] = i
answers = []
for i in range(N):
v = 2 * i
w = 2 * i + 1
rv = rank[comp[v]]
rw = rank[comp[w]]
if rv == rw:
print('Impossible')
exit()
if rv > rw:
answers.append((words[i][0], words[i][1:]))
else:
answers.append((words[i][:2], words[i][2]))
for a, b in answers:
print(a,b)
maspy