結果
| 問題 |
No.430 文字列検索
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2024-08-24 10:46:15 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 2,322 bytes |
| コンパイル時間 | 690 ms |
| コンパイル使用メモリ | 70,912 KB |
| 実行使用メモリ | 10,496 KB |
| 最終ジャッジ日時 | 2024-11-10 01:12:37 |
| 合計ジャッジ時間 | 4,059 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | -- * 4 |
| other | AC * 1 TLE * 1 -- * 12 |
ソースコード
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// ハッシュ値を事前計算する関数
vector<long long> precompute_hashes(const string& text, int pattern_length, int a, int h) {
int text_length = text.size();
vector<long long> hashes;
long long text_hash = 0;
// 最初の部分文字列のハッシュを計算する
for (int i = 0; i < pattern_length; i++) {
text_hash = (a * text_hash + text[i]) % h;
}
hashes.push_back(text_hash);
long long a_l = 1;
for (int i = 0; i < pattern_length; i++) {
a_l = (a_l * a) % h;
}
for (int i = 1; i <= text_length - pattern_length; i++) {
// ローリングハッシュを使って次の部分文字列のハッシュを計算する
text_hash = (text_hash * a - a_l * text[i - 1] + text[i + pattern_length - 1]) % h;
if (text_hash < 0) {
text_hash += h;
}
hashes.push_back(text_hash);
}
return hashes;
}
// ローリングハッシュを使ってパターンの出現回数を数える関数
int rolling_hash(const string& text, const string& pattern, const vector<long long>& precomputed_hashes, int a, int h) {
int pattern_length = pattern.size();
long long pattern_hash = 0;
// パターンのハッシュを計算する
for (int i = 0; i < pattern_length; i++) {
pattern_hash = (a * pattern_hash + pattern[i]) % h;
}
// 事前計算されたハッシュ値とパターンのハッシュを比較する
int count = 0;
for (const auto& hash_value : precomputed_hashes) {
if (hash_value == pattern_hash) {
count++;
}
}
return count;
}
int main() {
const int a = 31;
const int h = 998244353;
string S;
cin >> S;
int M;
cin >> M;
int ans = 0;
for (int i = 0; i < M; i++) {
string C;
cin >> C;
int pattern_length = C.size();
// 事前にS中の全ての部分文字列のハッシュを計算
vector<long long> precomputed_hashes = precompute_hashes(S, pattern_length, a, h);
// ハッシュを使ってパターンの出現回数をカウント
ans += rolling_hash(S, C, precomputed_hashes, a, h);
}
cout << ans << endl;
return 0;
}