题目链接:Keywords Search
AC自动机入门贴:自动机算法详解 (可能我比较菜,博主对Insert()和build_ac_automation()两个函数的解析没看太懂,我建议和我有同样状况的朋友选择看代码理解算法思想)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<map>
#include<set>
#include<cstdlib>
#define mem(a,b) memset(a,b,sizeof(a))
#define INF 0x7fffffff
typedef long long ll;
using namespace std;
const int kind_num = 26;
struct node{
node *fail;
node *next[kind_num];
int countt;
node(){
fail = NULL;
countt = 0;
memset(next,NULL,sizeof(next));
}
}*q[500010];
char keyword[51];
char str[1000010];
int head,tail;
void Insert(char *str,node *root){
node *p = root;
int i = 0,kind;
while(str[i]){
kind = str[i] - 'a';
if(p -> next[kind] == NULL){
p -> next[kind] = new node();
}
p = p -> next[kind];
i++;
}
p -> countt++;//用++,可能有多个相同的单词
}
void build_ac_automation(node *root){
int i;
root -> fail = NULL;
q[head++] = root;
while(head != tail){
node *tmp = q[tail++];
node *p = NULL;
for(int i = 0; i < 26; i++){
if(tmp -> next[i] != NULL){
if(tmp == root) tmp -> next[i] -> fail = root;
else{
p = tmp -> fail;
while(p != NULL){
if(p -> next[i] != NULL){
tmp -> next[i] -> fail = p -> next[i];
break;
}
p = p -> fail;
}
if(p == NULL) tmp -> next[i] -> fail = root;
}
q[head++] = tmp -> next[i];
}
}
}
}
int query(node *root){
int i = 0,cnt = 0,kind;
node *p = root;
while(str[i] != '\0'){
kind = str[i] - 'a';
while(p ->next[kind] == NULL && p != root) p = p -> fail;
p = p -> next[kind];
p = (p == NULL)?root:p;
node *tmp = p;
while(tmp != root && tmp -> countt != -1){
cnt += tmp -> countt;
tmp -> countt = -1;
tmp = tmp -> fail;
}
i++;
}
return cnt;
}
void dele(node *root){
int i;
for(int i = 0; i < kind_num; i++){
if(root -> next[i] != NULL){
dele(root -> next[i]);
}
}
free(root);
}
int main(){
int n,t;
scanf("%d",&t);
while(t--){
head = tail = 0;
node *root = new node();
scanf("%d",&n);
getchar();
for(int i = 0; i < n; i++){
gets(keyword);
Insert(keyword,root);
}
build_ac_automation(root);
scanf("%s",str);
printf("%d\n",query(root));
dele(root);
}
return 0;
}