結果
| 問題 |
No.430 文字列検索
|
| コンテスト | |
| ユーザー |
kazuma
|
| 提出日時 | 2017-07-25 23:12:35 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 39 ms / 2,000 ms |
| コード長 | 1,893 bytes |
| コンパイル時間 | 2,335 ms |
| コンパイル使用メモリ | 206,312 KB |
| 最終ジャッジ日時 | 2025-01-05 01:49:17 |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 14 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
class Aho_Corasick {
struct node {
node *no;
vector<node*> next;
vector<int> matched;
node() : no(nullptr), next(128, nullptr) {}
~node() { for (auto ite : next) if (ite != nullptr) delete ite; }
};
vector<int> unite(const vector<int>& a, const vector<int>& b) {
vector<int> res;
set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(res));
return res;
}
int K;
node *root;
public:
Aho_Corasick(const vector<string>& Ts) : K(Ts.size()), root(new node) {
node *now;
root->no = root;
for (int i = 0; i < K; i++) {
auto &T = Ts[i];
now = root;
for (auto c : T) {
if (now->next[c] == nullptr) {
now->next[c] = new node;
}
now = now->next[c];
}
now->matched.push_back(i);
}
queue<node*> q;
for (int i = 0; i < 128; i++) {
if (root->next[i] == nullptr) {
root->next[i] = root;
}
else {
root->next[i]->no = root;
q.push(root->next[i]);
}
}
while (!q.empty()) {
now = q.front(); q.pop();
for (int i = 0; i < 128; i++) {
if (now->next[i] != nullptr) {
node *nx = now->no;
while (nx->next[i] == nullptr) {
nx = nx->no;
}
now->next[i]->no = nx->next[i];
now->next[i]->matched = unite(now->next[i]->matched, nx->next[i]->matched);
q.push(now->next[i]);
}
}
}
}
vector<int> count(const string& S) {
vector<int> res(K);
node *now = root;
for (auto c : S) {
while (now->next[c] == nullptr) {
now = now->no;
}
now = now->next[c];
for (auto k : now->matched) {
res[k]++;
}
}
return res;
}
};
int main()
{
string S;
int M;
cin >> S >> M;
vector<string> C(M);
for (int i = 0; i < M; i++) {
cin >> C[i];
}
Aho_Corasick aho(C);
auto cnt = aho.count(S);
ll res = 0;
for (auto t : cnt) {
res += t;
}
cout << res << endl;
return 0;
}
kazuma