結果

問題 No.430 文字列検索
ユーザー RainkunchRainkunch
提出日時 2022-09-27 11:45:13
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 240 ms / 2,000 ms
コード長 1,376 bytes
コンパイル時間 280 ms
コンパイル使用メモリ 87,236 KB
実行使用メモリ 145,648 KB
最終ジャッジ日時 2023-08-24 03:44:12
合計ジャッジ時間 3,810 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 91 ms
71,744 KB
testcase_01 AC 240 ms
145,648 KB
testcase_02 AC 147 ms
81,864 KB
testcase_03 AC 149 ms
81,708 KB
testcase_04 AC 89 ms
71,772 KB
testcase_05 AC 88 ms
71,892 KB
testcase_06 AC 86 ms
71,560 KB
testcase_07 AC 89 ms
71,360 KB
testcase_08 AC 194 ms
139,080 KB
testcase_09 AC 97 ms
77,008 KB
testcase_10 AC 114 ms
82,544 KB
testcase_11 AC 170 ms
90,784 KB
testcase_12 AC 173 ms
90,832 KB
testcase_13 AC 173 ms
90,700 KB
testcase_14 AC 164 ms
86,000 KB
testcase_15 AC 159 ms
84,008 KB
testcase_16 AC 150 ms
81,344 KB
testcase_17 AC 149 ms
81,656 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
class RollingHash():
    def __init__(self, str, MOD, B):
        self.hash = [0]*(len(str)+1)
        self.B_power = [1]*(max(11,len(str)+1))
        for i in range(10):
            self.B_power[i+1] = self.B_power[i]*B % MOD
        for i in range(len(str)): # 累積和的に求めていく
            self.hash[i+1] = (self.hash[i]*B + ord(str[i])) % MOD
            self.B_power[i+1] = self.B_power[i]*B % MOD

    def Bad_rollinghash(self,s): # ローリングハッシュの定義
        H = 0 
        for i,si in enumerate(s):
            H += ord(si)*self.B_power[len(s)-i-1]
            H %= MOD
        return H # これでは毎回O(m)かかってしまい、意味がない

    def get_hash(self,l,r): # str[l,r)のハッシュ値を求める
        return (self.hash[r] - self.hash[l]*self.B_power[r-l]) % MOD

    def debug(self):
        print(self.hash)
        print(self.B_power)

S = list(input())
M = int(input())
MOD = 10**9+9
B = 37
d = defaultdict(int)

Ryh = RollingHash(S,MOD,B)
# Cは高々10文字なので、Sの1~10文字分のハッシュ値をdictに記録していく
for width in range(1,11):
    for i in range(len(S)-width+1):
        h = Ryh.get_hash(i,i+width)
        d[h] += 1

ans = 0
for i in range(M):
    C = list(input())
    C_hash = Ryh.Bad_rollinghash(C)
    ans += d[C_hash]
print(ans)
0