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; } };
相关文章推荐
- ac自动机模板
- AC自动机模板
- [模板]AC自动机 洛谷3808 AC自动机
- hdu 2222 AC自动机模板(非指针)
- HDOJ2222Keywords Search【AC自动机模板题】
- ac自动机代码模板
- AC自动机 模板
- luogu3796 【模板】AC自动机(加强版)
- AC自动机模板 2
- HDOJ-2222 (AC自动机模板)
- HDU2222 AC自动机模板
- (模板)AC自动机
- HDU 3065 病毒侵袭持续中(AC自动机模板)
- AC自动机模板
- hdu2222(ac自动机模板)
- 数据结构--AC自动机--模板2
- AC自动机(Aho-Corasick automation)模板 HDU:2222
- AC自动机 模板
- 【模板】AC自动机(加强版) 洛谷3796 AC自动机
- AC自动机模板