Keywords Search HDU - 2222(ac自动机板题。。)
Posted wtsruvf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Keywords Search HDU - 2222(ac自动机板题。。)相关的知识,希望对你有一定的参考价值。
求一个字符串上有多少个匹配的单词
看着卿学姐的板子写的
#include <iostream> #include <cstdio> #include <sstream> #include <cstring> #include <map> #include <set> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <cmath> #define rap(i, a, n) for(int i=a; i<=n; i++) #define rep(i, a, n) for(int i=a; i<n; i++) #define lap(i, a, n) for(int i=n; i>=a; i--) #define lep(i, a, n) for(int i=n; i>a; i--) #define MOD 2018 #define LL long long #define ULL unsigned long long #define Pair pair<int, int> #define mem(a, b) memset(a, b, sizeof(a)) #define _ ios_base::sync_with_stdio(0),cin.tie(0) //freopen("1.txt", "r", stdin); using namespace std; const int maxn = 1000010, maxm = 500005, INF = 0x7fffffff; int tot; queue<int> q; struct state { int next[26]; int fail, cnt; }trie[500005]; void init() { while(!q.empty()) q.pop(); for(int i=0; i<maxm; i++) { mem(trie[i].next, 0); trie[i].fail = trie[i].cnt = 0; } tot = 0; } void insert(char *s) { int n = strlen(s); int rt = 0; for(int i=0;i<n; i++) { int x = s[i] - ‘a‘; if(!trie[rt].next[x]) { trie[rt].next[x] = ++tot; } rt = trie[rt].next[x]; } trie[rt].cnt++; } void build() { trie[0].fail= -1; q.push(0); while(!q.empty()) { int u = q.front(); q.pop(); for(int i=0; i<26; i++) { if(trie[u].next[i]) { if(u == 0) trie[trie[u].next[i]].fail = 0; else{ int v = trie[u].fail; while(v != -1) { if(trie[v].next[i]) { trie[trie[u].next[i]].fail = trie[v].next[i]; break; } v = trie[v].fail; } if(v == -1) trie[trie[u].next[i]].fail = 0; } q.push(trie[u].next[i]); } } } } int Get(int u) { int res = 0; while(u) { res = res + trie[u].cnt; trie[u].cnt = 0; u = trie[u].fail; } return res; } int math(char *s) { int n = strlen(s); int rt = 0, res = 0; for(int i=0; i<n; i++) { int x = s[i] - ‘a‘; if(trie[rt].next[x]) //如果有儿子 就直接下传 rt = trie[rt].next[x]; else //如果没有 就去fail去找 { int p = trie[rt].fail; while(p != -1 && trie[p].next[x] == 0) p = trie[p].fail; if(p == -1) rt = 0; //一直没找到 则返回祖结点 else rt = trie[p].next[x]; } if(trie[rt].cnt) //如果以这个点为后缀的串还没有被匹配 则匹配 res = res + Get(rt); } return res; } int T, n; char s[maxn]; int main() { scanf("%d", &T); while(T--) { init(); scanf("%d", &n); rap(i, 1, n) { scanf("%s", s); insert(s); } build(); scanf("%s", s); printf("%d ", math(s)); } return 0; }
以上是关于Keywords Search HDU - 2222(ac自动机板题。。)的主要内容,如果未能解决你的问题,请参考以下文章