HDU 2222 (AC自动机)
2017-07-16 17:28
351 查看
HDU 2222 Keywords search
Problem : 给若干个模式串,询问目标串中出现了多少个模式串。Solution : 复习了一下AC自动机。需要注意AC自动机中的fail,和next的含义。fail指向了一个最长的与当前匹配出具有相同后缀的一个前缀节点,next用来转移下一个字符,指向最远可以匹配的位置。另外,在目标串匹配时,需要用一个temp指针不断经过fail指针向前跳转,所有经过的节点都是符合的。
#include <iostream> #include <cstring> #include <queue> using namespace std; const int N = 500008; struct AC_Automan { int next [26]; int fail ; int cnt ; int root, tot; int newnode() { for (int i = 0; i < 26; ++i) next[tot][i] = -1; fail[tot] = -1; cnt[tot] = 0; return tot++; } void clear() { tot = 0; root = newnode(); } void insert(const string &s) { int p = root; for (int i = 0, len = s.length(); i < len; ++i) { if (next[p][s[i] - 'a'] == -1) next[p][s[i] - 'a'] = newnode(); p = next[p][s[i] - 'a']; } ++cnt[p]; } void build() { queue <int> Q; Q.push(root); while (!Q.empty()) { int p = Q.front(); Q.pop(); for (int i = 0; i < 26; ++i) { if (~next[p][i]) { if (p == root) fail[next[p][i]] = root; else fail[next[p][i]] = next[fail[p]][i]; Q.push(next[p][i]); } else { if (p == root) next[p][i] = root; else next[p][i] = next[fail[p]][i]; } } } } int solve(const string &t) { int p = root, ans = 0; for (int i = 0, len = t.length(); i < len; ++i) { p = next[p][t[i] - 'a']; for (int temp = p; temp != root && cnt[temp] != -1; temp = fail[temp]) { ans += cnt[temp]; cnt[temp] = -1; } } return ans; } }ac; int main() { cin.sync_with_stdio(0); int T; cin >> T; for (int cas = 1; cas <= T; ++cas) { ac.clear(); int n; cin >> n; for (int i = 0; i < n; ++i) { string s; cin >> s; ac.insert(s); } ac.build(); string t; cin >> t; cout << ac.solve(t) << endl; } }
相关文章推荐
- hdu 2222 Keywords Search(AC自动机模版题)
- HDU 2222 Keywords Search (AC自动机)
- hdu 2222 Keywords Search(AC自动机模板题)
- hdu 2222 Keywords Search(AC自动机入门题)
- hdu 2222 Keywords Search(AC自动机)
- HDU 2222(AC 自动机)
- HDU 2222 Keywords Search(AC自动机)
- HDU 2222 最简单的AC自动机套模板应用
- hdu 2222(ac自动机)
- hdu 2222(Keywords Search) (AC自动机)
- HDU 2222 Keywords Search (AC 自动机)
- hdu 2222 Keywords Search(AC自动机模板题)
- HDU 2222:Keywords Search(AC自动机入门题)
- HDU 2222 Keywords Search (AC自动机模板题)
- ac自动机 hdu 2222
- hdu 2222(AC自动机入门题)
- HDU2222 Keywords Search(AC自动机)
- hdu_2222: Keywords Search(AC自动机模板题)
- hdu 2222 Keywords Search(AC自动机)
- 【HDU 2222】Keywords Search(AC自动机)