結果

問題 No.430 文字列検索
ユーザー matsu7874matsu7874
提出日時 2016-10-02 23:28:06
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
WA  
実行時間 -
コード長 2,095 bytes
コンパイル時間 98 ms
コンパイル使用メモリ 10,912 KB
実行使用メモリ 16,904 KB
最終ジャッジ日時 2023-08-13 18:06:48
合計ジャッジ時間 1,883 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 16 ms
8,092 KB
testcase_01 WA -
testcase_02 AC 61 ms
10,372 KB
testcase_03 AC 60 ms
10,532 KB
testcase_04 AC 16 ms
8,052 KB
testcase_05 AC 16 ms
8,092 KB
testcase_06 AC 15 ms
8,000 KB
testcase_07 AC 16 ms
7,964 KB
testcase_08 AC 34 ms
8,352 KB
testcase_09 AC 19 ms
8,504 KB
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 AC 71 ms
11,400 KB
testcase_16 WA -
testcase_17 AC 71 ms
11,396 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class AhoCorasick:
    class State:
        def __init__(self, id):
            self.id = id
            self.next = {}
        def has_key(self, x):
            return x in self.next
    
    def __init__(self, terms):
        self.state = [AhoCorasick.State(0)]
        self.output = [[]]
        self._make_goto(terms)
        self._make_failure()
    
    def _make_goto(self, terms):
        for term in terms:
            cur = self.state[0]
            for x in term:
                if not cur.has_key(x):
                    new = AhoCorasick.State(len(self.state))
                    cur.next[x] = new
                    self.state.append(new)
                    self.output.append([])
                cur = cur.next[x]
            s = cur.id
            self.output[s].append(term)

    def _make_failure(self):
        failure = [0] * len(self.state)
        queue = [0]
        while queue:
            s = queue.pop()
            for x in self.state[s].next.keys():
                next = self.g(s,x)
                if next is not None:
                    queue.append(next)
                if s != 0:
                    f = failure[s]
                    while self.g(f, x) is None:
                        f = failure[f]
                    failure[next] = self.g(f, x)
                    self.output[next].extend(self.output[failure[next]])
        self.failure = failure
    def g(self, s, x):
        if x in self.state[s].next:
            return self.state[s].next[x].id
        else:
            if s == 0:
                return 0
            else:
                return None
    def count(self, text):
        s = 0
        total = 0
        for c in text:
            while self.g(s, c) is None: 
                s = self.failure[s]
            s = self.g(s, c)
            total += len(self.output[s])
            # for i,x in enumerate(self.output[s]):
                # print('%d,%d => %s' % (i-len(x)+1, i, x))
        return total

text = input()
m = int(input())
terms = [input() for i in range(m)]            
ac = AhoCorasick(terms)
print(ac.count(text))
0