結果
問題 |
No.430 文字列検索
|
ユーザー |
|
提出日時 | 2022-10-12 23:31:53 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 10 ms / 2,000 ms |
コード長 | 2,416 bytes |
コンパイル時間 | 2,362 ms |
コンパイル使用メモリ | 207,340 KB |
最終ジャッジ日時 | 2025-02-08 02:19:03 |
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 14 |
ソースコード
#include <bits/stdc++.h> using namespace std; using i64 = long long; using VI = vector<int>; using pii = pair<int, int>; template <class Node> struct trie { vector<Node> tr; trie() { tr.push_back(Node()); }; int add(const string &s) { int n = s.size(); int p = 0; for (int i = 0; i < n; i++) { int c = s[i] - 'A'; if (!tr[p][c]) { tr[p][c] = tr.size(); tr.emplace_back(tr[p][c], tr[p].dep + 1); } p = tr[p][c]; } return p; } int size() const { return tr.size(); } }; template <class Node> struct ACAutomaton : public trie<Node> { vector<int> fail; ACAutomaton() { this->tr.push_back(Node()); }; void BuildAC() { fail.resize(this->tr.size()); queue<int> Q; for (int i = 0; i < 26; i++) if (this->tr[0][i]) Q.push(this->tr[0][i]); while (!Q.empty()) { int u = Q.front(); Q.pop(); for (int i = 0; i < 26; i++) { if (this->tr[u][i]) fail[this->tr[u][i]] = this->tr[fail[u]][i], Q.push(this->tr[u][i]); else this->tr[u][i] = this->tr[fail[u]][i]; } } return; } }; struct TrieNode { TrieNode() { id = 0, dep = 0, nxt = array<int, 26>(); }; TrieNode(int _id, int _dep) : id(_id), dep(_dep) {} int id; int dep; array<int, 26> nxt = {}; int &operator[](const int x) { return this->nxt[x]; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; int m; cin >> s >> m; ACAutomaton<TrieNode> ac; vector<int> pos(m + 1); for (int i = 1; i <= m; i++) { string res; cin >> res; pos[i] = ac.add(res); } ac.BuildAC(); vector<int> val(ac.size()); vector<vector<int>> adj(ac.size()); for (int i = 0; i < ac.size(); i++) { if (i != ac.fail[i]) adj[ac.fail[i]].push_back(i); } int p = 0; for (auto it : s) { p = ac.tr[p][it - 'A']; val[p]++; } function<void(int)> dfs = [&](int u) { for (auto v : adj[u]) { dfs(v); val[u] += val[v]; } }; dfs(0); int ans = 0; for (int i = 1; i <= m; i++) ans += val[pos[i]]; cout << ans << endl; return 0; }