結果

問題 No.517 壊れたアクセサリー
ユーザー はむ吉🐹はむ吉🐹
提出日時 2017-06-03 14:51:44
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 31 ms / 2,000 ms
コード長 2,910 bytes
コンパイル時間 948 ms
コンパイル使用メモリ 11,820 KB
実行使用メモリ 10,440 KB
最終ジャッジ日時 2023-10-22 02:58:23
合計ジャッジ時間 2,307 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 31 ms
10,432 KB
testcase_01 AC 31 ms
10,432 KB
testcase_02 AC 31 ms
10,432 KB
testcase_03 AC 31 ms
10,432 KB
testcase_04 AC 31 ms
10,432 KB
testcase_05 AC 31 ms
10,432 KB
testcase_06 AC 30 ms
10,432 KB
testcase_07 AC 30 ms
10,432 KB
testcase_08 AC 30 ms
10,432 KB
testcase_09 AC 31 ms
10,432 KB
testcase_10 AC 31 ms
10,432 KB
testcase_11 AC 31 ms
10,432 KB
testcase_12 AC 30 ms
10,432 KB
testcase_13 AC 31 ms
10,432 KB
testcase_14 AC 31 ms
10,440 KB
testcase_15 AC 31 ms
10,440 KB
testcase_16 AC 31 ms
10,436 KB
testcase_17 AC 31 ms
10,436 KB
testcase_18 AC 30 ms
10,436 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3

# Thanks: http://hamayanhamayan.hatenablog.jp/entry/2017/05/29/013706


import array
import heapq
import itertools


class TopologicalSortError(Exception):
    pass


def topological_sort(num_vs, adj_vs):
    """ Performs topological sorting of the given DAG.

    This function computes the lexicographically least
    topological order of the given DAG.

    :param num_vs int: The number of vertices.
    :param adj_vs list: The adjacency list.
    :return: The lexicographically least topological order.
    :rtype: :obj:`array.array`
    :raises TopologicalSortError: if the given graph is not a DAG
    """
    in_deg = array.array("L", (0 for _ in range(num_vs)))
    for dests in adj_vs:
        for dest in dests:
            in_deg[dest] += 1
    sorted_vs = array.array("L")
    pq = []
    for s in range(num_vs):
        if in_deg[s] == 0:
            heapq.heappush(pq, s)
    while pq:
        u = heapq.heappop(pq)
        sorted_vs.append(u)
        for v in adj_vs[u]:
            in_deg[v] -= 1
            if in_deg[v] == 0:
                heapq.heappush(pq, v)
    if all(x == 0 for x in in_deg):
        return sorted_vs
    else:
        raise TopologicalSortError("The graph has a cycle")


def solve(yukis, kodas):
    all_chars = "".join(sorted(itertools.chain(*yukis)))
    num_vs = len(all_chars)
    char_to_idx = dict()
    for i, c in enumerate(all_chars):
        # 文字 -> 頂点番号の対照表
        char_to_idx[c] = i
    adj_vs = [set() for _ in range(num_vs)]
    for frag in itertools.chain(yukis, kodas):
        for c1, c2 in zip(frag[:-1], frag[1:]):
            # 隣接する二つの文字c1, c2について
            # c1 -> c2という有向辺があると考える
            adj_vs[char_to_idx[c1]].add(char_to_idx[c2])
    try:
        res = topological_sort(num_vs, adj_vs)
    except TopologicalSortError:
        return None
    for i, j in zip(res[:-1], res[1:]):
        # ソートされた頂点の列において、
        # どの隣接する2頂点の間にも辺があるか?
        if j not in adj_vs[i]:
            return None
    return "".join(all_chars[i] for i in res)


def main():
    n = int(input())
    yukis = [input() for _ in range(n)]
    m = int(input())
    kodas = [input() for _ in range(m)]
    ans = solve(yukis, kodas)
    if ans is None:
        print(-1)
    else:
        print(ans)


if __name__ == '__main__':
    main()




















#    ∧    /|
#   / ∧__/ |
#  / _   _ ヽ
# `/ く◎> く◎〉|
# |   ̄    ̄ |
# 人       ノ  _
#  \___  /  ||
#   /   ̄| ̄   ||
#   /    ヽ___ノ|
#  |         /
#  | /|      |
#   L/ |  /|    /
#     |_/ | /|  /
#       |/ ヽ/
0