您的位置:首页 > 其它

AC自动机模板

2014-02-26 18:08 190 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: