hdu 2222
2014-07-30 12:16
183 查看
#include<stdio.h> #include<string.h> #define N 500000 struct node { node *fail; node *next[26]; int count; node() { count=0; memset(next,0,sizeof(next)); fail=NULL; } }*q ; node *root; int head,tail; char str[N*2+10]; void insert(char *str) { int i,n; node *p=root; for(i=0;str[i]!='\0';i++) { n=str[i]-'a'; if(p->next ==NULL) p->next =new node(); p=p->next ; } p->count++; } void build_ac_automation() { int i; q[head++]=root; root->fail=NULL; while(head!=tail) { node *temp=q[tail++]; node *p=NULL; for(i=0;i<26;i++) { if(temp->next[i]!=NULL) { if(temp==root) temp->next[i]->fail=root; else { p=temp->fail; while(p!=NULL) { if(p->next[i]!=NULL) { temp->next[i]->fail=p->next[i]; break; } p=p->fail; } if(p==NULL) temp->next[i]->fail=root; } q[head++]=temp->next[i]; } } } } int query(char *str) { int i=0,cnt=0; node *p=root; while(str[i]) { int len=str[i]-'a'; while(p->next[len]==NULL&&p!=root) p=p->fail; p=p->next[len]; p=(p==NULL)?root:p; node *temp=p; while(temp!=root&&temp->count!=-1) { cnt+=temp->count; temp->count=-1; temp=temp->fail; } i++; } return cnt; } int main() { int t,n,i; char s[100]; scanf("%d",&t); while(t--) { scanf("%d",&n); root=new node(); for(i=1;i<=n;i++) { scanf("%s",s); insert(s); } head=tail=0; build_ac_automation(); scanf("%s",str); printf("%d\n",query(str)); } return 0; }
相关文章推荐
- HDU 2222:Keywords Search(AC自动机入门题)
- hdu 2222 Keywords Search
- hdu 2222 Keywords Search(AC自动机模板题)
- HDU 2222 Keywords Search(AC自动机)
- HDU 2222 AC自动机
- hdu 2222 ac自动机模板题
- HDU 2222 Keywords Search(AC自动机)
- HDU 2222 Keywords Search(AC自动机/模板题)
- hdu-2222
- hdu_2222_Keywords Search(AC自动机板子)
- hdu 2222
- HDU 2222 Keywords Search
- hdu 2222 Keywords Search(AC 自动机)
- hdu 2222 Keywords Search
- HDU 2222
- HDU 2222 AC自动机
- 【hdu 2222】Keywords Search
- 文章标题 HDU 2222 : Keywords Search (AC自动机模板)
- hdu 2222 ac自动机模板
- hdu 2222 AC自动机