結果
| 問題 |
No.430 文字列検索
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2024-08-24 10:45:30 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 1,825 bytes |
| コンパイル時間 | 233 ms |
| コンパイル使用メモリ | 82,432 KB |
| 実行使用メモリ | 213,760 KB |
| 最終ジャッジ日時 | 2024-11-10 01:12:36 |
| 合計ジャッジ時間 | 3,539 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | -- * 4 |
| other | AC * 1 TLE * 1 -- * 12 |
ソースコード
def precompute_hashes(text: str, pattern_length: int, a: int, h: int) -> list:
text_length = len(text)
hashes = []
text_hash = 0
# 最初の部分文字列のハッシュを計算する
for i in range(pattern_length):
text_hash = (a * text_hash + ord(text[i])) % h
hashes.append(text_hash)
a_l = pow(a, pattern_length, h) # a^l を計算
for i in range(1, text_length - pattern_length + 1):
# ローリングハッシュを使って次の部分文字列のハッシュを計算する
text_hash = (text_hash * a - a_l * ord(text[i - 1]) + ord(text[i + pattern_length - 1])) % h
if text_hash < 0:
text_hash += h
hashes.append(text_hash)
return hashes
def rolling_hash(text: str, pattern: str, precomputed_hashes: list, a: int, h: int) -> int:
pattern_length = len(pattern)
pattern_hash = 0
# パターンのハッシュを計算する
for i in range(pattern_length):
pattern_hash = (a * pattern_hash + ord(pattern[i])) % h
# 事前計算されたハッシュ値とパターンのハッシュを比較する
return sum(1 for hash_value in precomputed_hashes if hash_value == pattern_hash)
def main():
a = 31
h = 998244353
S = input().strip()
M = int(input())
ans = 0
text_length = len(S)
for _ in range(M):
C = input().strip()
pattern_length = len(C)
# 事前にS中の全ての部分文字列のハッシュを計算
precomputed_hashes = precompute_hashes(S, pattern_length, a, h)
# ハッシュを使ってパターンの出現回数をカウント
ans += rolling_hash(S, C, precomputed_hashes, a, h)
print(ans)
if __name__ == "__main__":
main()