結果
問題 |
No.430 文字列検索
|
ユーザー |
|
提出日時 | 2024-08-24 10:42:14 |
言語 | PyPy3 (7.3.15) |
結果 |
WA
|
実行時間 | - |
コード長 | 1,873 bytes |
コンパイル時間 | 187 ms |
コンパイル使用メモリ | 82,304 KB |
実行使用メモリ | 94,464 KB |
最終ジャッジ日時 | 2024-11-10 01:12:33 |
合計ジャッジ時間 | 4,629 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | WA * 1 RE * 3 |
other | AC * 1 WA * 12 RE * 1 |
ソースコード
def precompute_all_hashes(text: str, max_pattern_length: int, a: int, h: int) -> dict[int, list[int]]: text_length = len(text) hash_dict = {} for length in range(1, max_pattern_length + 1): current_hash = 0 a_l = pow(a, length - 1, h) # a^(length-1) を計算しておく # 最初の部分文字列のハッシュを計算 for i in range(length): current_hash = (current_hash * a + ord(text[i])) % h hash_dict.setdefault(length, []).append(current_hash) # 残りの部分文字列のハッシュを計算 for i in range(1, text_length - length + 1): current_hash = (current_hash * a - ord(text[i - 1]) * a_l + ord(text[i + length - 1])) % h if current_hash < 0: current_hash += h hash_dict[length].append(current_hash) return hash_dict def rolling_hash(text: str, patterns: list[str], max_pattern_length: int = 10, a: int = 31, h: int = 998244353) -> int: text_length = len(text) hash_dict = precompute_all_hashes(text, max_pattern_length, a, h) counter = 0 for pattern in patterns: pattern_length = len(pattern) if pattern_length > text_length or pattern_length > max_pattern_length: continue pattern_hash = 0 for char in pattern: pattern_hash = (pattern_hash * a + ord(char)) % h # パターンのハッシュがテキストの部分文字列のハッシュに含まれているかチェック if pattern_hash in hash_dict.get(pattern_length, []): counter += 1 return counter def main(): S = input() M = int(input()) patterns = [input() for _ in range(M)] ans = rolling_hash(S, patterns) print(ans) if __name__ == "__main__": main()