const int kind=26;
struct AC_Automata{
struct node{
node *child[kind];
node *fail;
int count;
node(){
for(int i=0;i<kind;++i) child[i]=NULL;
count=0;
fail=NULL;
}
};
node *root;
AC_Automata(){
root=new node();
}
inline int id(char c){return c-'a';}
void insert(char *s){
node *now;
now=root;
for(int i=0;s[i];++i){
int t=id(s[i]);
if(now->child[t]!=NULL) now=now->child[t];
else {
now->child[t]=new node();
now=now->child[t];
}
}
now->count++;
}
void build(){
queue<node*>q;
while(!q.empty()) q.pop();
q.push(root);
while(!q.empty()){
node *now=q.front(),*p=NULL; q.pop();
for(int i=0;i<kind;++i){
if(now->child[i]==NULL) continue;
if(now==root) now->child[i]->fail=root;
else {
p=now->fail;
while(p!=NULL){
if(p->child[i]!=NULL){
now->child[i]->fail=p->child[i];
break;
}
p=p->fail;
}
if(p==NULL) now->child[i]->fail=root;
}
q.push(now->child[i]);
}
}
}
int query(char *s){
int ans=0;
node *now=root,*temp;
for(int i=0;s[i];++i){
int t=id(s[i]);
while(now->child[t]==NULL && now!=root) now=now->fail;
now=now->child[t];
if(now==NULL) now=root;
temp=now;
while(temp!=root && temp->count!=-1){
ans+=temp->count;
temp->count=-1;
temp=temp->fail;
}
}
return ans;
}
};
AC自动机模板
最新推荐文章于 2018-10-05 22:17:32 发布