結果

問題 No.430 文字列検索
ユーザー neterukunneterukun
提出日時 2021-06-12 17:13:59
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 221 ms / 2,000 ms
コード長 1,690 bytes
コンパイル時間 361 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 86,528 KB
最終ジャッジ日時 2024-05-09 20:43:49
合計ジャッジ時間 3,597 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 48 ms
54,016 KB
testcase_01 AC 219 ms
86,528 KB
testcase_02 AC 125 ms
77,824 KB
testcase_03 AC 125 ms
77,440 KB
testcase_04 AC 48 ms
53,888 KB
testcase_05 AC 47 ms
53,632 KB
testcase_06 AC 50 ms
53,760 KB
testcase_07 AC 53 ms
54,016 KB
testcase_08 AC 93 ms
72,320 KB
testcase_09 AC 68 ms
64,640 KB
testcase_10 AC 81 ms
66,944 KB
testcase_11 AC 216 ms
82,688 KB
testcase_12 AC 208 ms
83,456 KB
testcase_13 AC 221 ms
83,968 KB
testcase_14 AC 188 ms
81,408 KB
testcase_15 AC 163 ms
80,384 KB
testcase_16 AC 161 ms
80,128 KB
testcase_17 AC 157 ms
79,744 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque


class Node:
    def __init__(self):
        self.child = {}
        self.failure = None
        self.valid = 0

    def set_child(self, s):
        self.child[s] = Node()

    def get_child(self, s):
        if s not in self.child:
            return None
        return self.child[s]


class AhoCorasick:
    def __init__(self):
        self.root = Node()

    def add(self, pattern):
        ptr = self.root
        for s in pattern:
            if ptr.get_child(s) is None:
                ptr.set_child(s)
            ptr = ptr.get_child(s)
        ptr.valid += 1

    def build_failure(self):
        queue = deque()
        for s in self.root.child:
            ptrch = self.root.child[s]
            ptrch.failure = self.root
            queue.append(ptrch)
        while queue:
            ptr = queue.popleft()
            ptr.valid += ptr.failure.valid
            for s in ptr.child:
                ptrch = ptr.child[s]
                f = ptr.failure
                while f is not None and f.get_child(s) is None:
                    f = f.failure
                ptrch.failure = f.get_child(s) if f is not None else self.root
                queue.append(ptrch)

    def match_count(self, text):
        ptr = self.root
        res = 0
        for s in text:
            while ptr is not None and ptr.get_child(s) is None:
                ptr = ptr.failure
            ptr = ptr.get_child(s) if ptr is not None else self.root
            res += ptr.valid
        return res


text = input()
m = int(input())
c = [input() for i in range(m)]


ac = AhoCorasick()
for string in c:
    ac.add(string)
ac.build_failure()
print(ac.match_count(text))
0