hdu 2222 ac自动机更新模板 for onSite contest

http://acm.split.hdu.edu.cn/showproblem.php?pid=2222

#include <cstdio>
#include <cstdlib>
#include <cstring>
const int maxn = + ;
const int N = ; struct AC {
int son[maxn][N], fail[maxn * N], endPos[maxn * N];
int t, root;
int create() {
++t;
for (int i = ; i < N; ++i) son[t][i] = NULL;
fail[t] = endPos[t] = NULL;
return t;
}
void init() {
t = ;
root = create();
}
int getID(char ch) {
return ch - 'a';
}
void toInsert(char str[]) {
int now = root;
for (int i = ; str[i]; ++i) {
int id = getID(str[i]);
if (son[now][id] == NULL) son[now][id] = create();
now = son[now][id];
}
endPos[now]++;
}
int que[maxn * N];
void buildFail() {
fail[root] = root;
int head = , tail = ;
for (int i = ; i < N; ++i) {
if (son[root][i] == NULL) son[root][i] = root;
else {
fail[son[root][i]] = root;
que[tail++] = son[root][i];
}
}
while (head < tail) {
int cur = que[head++];
for (int i = ; i < N; ++i) {
if (son[cur][i] == NULL) son[cur][i] = son[fail[cur]][i];
else {
fail[son[cur][i]] = son[fail[cur]][i]; //虚拟边已经存在
que[tail++] = son[cur][i];
}
}
}
}
int query(char str[]) {
int now = root, ans = ;
for (int i = ; str[i]; ++i) {
int id = getID(str[i]);
now = son[now][id];
int p = now;
while (p != root && endPos[p] != -) {
ans += endPos[p];
endPos[p] = -;
p = fail[p];
}
}
return ans;
}
} ac; char str[maxn];
void work () {
ac.init();
int n;
scanf("%d", &n);
while (n--) {
scanf("%s", str + );
ac.toInsert(str);
}
scanf("%s", str + );
ac.buildFail();
printf("%d\n", ac.query(str));
return ;
}
int main() {
#ifdef local
freopen("data.txt", "r", stdin);
#endif
int t;
scanf("%d", &t);
while (t--) {
work ();
}
return ;
}
上一篇:HDU 2222 AC自动机(模版题)


下一篇:HDU 2222 AC自动机模版题