HDU 2222 AC自动机模板题

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

AC自动机模板题

我现在对AC自动机的理解还一般,就贴一下我参考学习的两篇博客的链接:

http://blog.csdn.net/niushuai666/article/details/7002823

http://www.cppblog.com/menjitianya/archive/2014/07/10/207604.html

 #include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
char key[];
char des[];
struct node{
node *fail;
node *next[];
int cnt;
node(){
fail = NULL;
cnt = ;
for(int i = ;i<;i++)
next[i] = NULL;
}
};
node *root;
void insert(char *str){
node *head = root;
int len = strlen(str);
for(int i = ;i<len;i++){
int temp = str[i]-'a';
if(head->next[temp] == NULL)
head->next[temp] = new node();
head = head->next[temp];
}
head->cnt++;
}
void build(){
queue<node *>q;
q.push(root);
while(!q.empty()){
node *head = q.front();
q.pop();
for(int i = ;i<;i++){
if(head->next[i] != NULL){
if(head == root){
head->next[i]->fail = root;
}else{
node *temp = head->fail;
while(temp != NULL){
if(temp->next[i] != NULL){
head->next[i]->fail = temp->next[i];
break;
}
temp = temp->fail;
}
if(temp == NULL)
head->next[i]->fail = root;
}
q.push(head->next[i]);
}
}
}
}
int query(){
int len = strlen(des),ans = ;;
node *head = root;
for(int i = ;i<len;i++){
int index = des[i]-'a';
while(head->next[index] == NULL && head != root)
head = head->fail;
head = head->next[index];
if(head == NULL)
head = root;
node *temp = head;
while(temp!=root && temp->cnt!=-){
ans += temp->cnt;
temp->cnt = -;
temp = temp->fail;
}
}
return ans;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
root = new node();
int n;
scanf("%d",&n);
for(int i = ;i<n;i++){
scanf(" %s",key);
insert(key);
}
build();
scanf(" %s",des);
printf("%d\n",query());
}
return ;
}
上一篇:Windows Azure使用体验


下一篇:JSP常见指令