結果
問題 | No.517 壊れたアクセサリー |
ユーザー |
![]() |
提出日時 | 2025-03-31 17:48:37 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 39 ms / 2,000 ms |
コード長 | 2,281 bytes |
コンパイル時間 | 134 ms |
コンパイル使用メモリ | 82,276 KB |
実行使用メモリ | 54,088 KB |
最終ジャッジ日時 | 2025-03-31 17:49:47 |
合計ジャッジ時間 | 1,541 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 15 |
ソースコード
def main():import sysinput = sys.stdin.read().split()ptr = 0N = int(input[ptr])ptr += 1A = []for _ in range(N):A.append(input[ptr])ptr += 1M = int(input[ptr])ptr += 1B = []for _ in range(M):B.append(input[ptr])ptr += 1all_fragments = A + Bnext_char = {}prev_char = {}# Process all fragments to build next and prevfor frag in all_fragments:for i in range(len(frag) - 1):c = frag[i]d = frag[i + 1]# Check next conflictif c in next_char and next_char[c] != d:print(-1)return# Check prev conflictif d in prev_char and prev_char[d] != c:print(-1)returnnext_char[c] = dprev_char[d] = cchars = set()for frag in all_fragments:for c in frag:chars.add(c)chars = list(chars)total_chars = len(chars)# Find start nodes (no prev)start_nodes = []for c in chars:if c not in prev_char or prev_char[c] is None:start_nodes.append(c)# Check cycles and build chainsvisited = set()chains = []for s in start_nodes:if s in visited:continuecurrent = schain = []while True:if current in visited:# Cycle detectedprint(-1)returnchain.append(current)visited.add(current)if current not in next_char:breakcurrent = next_char[current]chains.append(chain)# Check if all characters are visitedif len(visited) != total_chars:print(-1)returnif len(chains) != 1:print(-1)return# Combine the chain into the candidate stringcandidate = ''.join(chains[0])# Verify that all fragments are present as substrings# This is technically redundant but included for safetyfor frag in all_fragments:f = ''.join(frag)if f not in candidate:print(-1)returnprint(candidate)if __name__ == "__main__":main()