AC自动机模板
来源:互联网 发布:java中base64 编辑:程序博客网 时间:2024/05/16 07:45
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
#include<stdio.h>#include<string.h>#include<stdlib.h>#define kind 26const int MAXN = 10000000;struct node{ int count; node *next[26]; node *fail; };node *q[MAXN]; char keyword[55];char str[1000010];int head,tail;node *root;void insert(char *word,node *root){ int index,len; node *p = root,*newnode; len = strlen(word); for(int i=0 ;i < len ; i++ ) { index=word[i]-'a'; if(!p->next[index]) { newnode=(struct node *)malloc(sizeof(struct node)); for(int j=0;j<26;j++) newnode->next[j]=0; newnode->count=0;newnode->fail=0; p->next[index]=newnode; } p=p->next[index]; } p->count++; }void build_ac_automation(node *root){ head=0;tail=1; q[head]=root; node *temp,*p; while(head<tail) { temp=q[head++]; for(int i=0;i< 26 ;i ++) { if(temp->next[i]) { if(temp==root)temp->next[i]->fail=root; else { p=temp->fail; while(p){ if(p->next[i]){ temp->next[i]->fail=p->next[i]; break; } p=p->fail; } if(!p)temp->next[i]->fail=root; } q[tail++]=temp->next[i]; } } }}int query(node *root){ int i,cnt=0,index,len=strlen(str); node *p=root; for(i=0; i < len ;i ++) { index=str[i]-'a'; while( !p->next[index] && p != root)
{
p=p->fail;
} p=p->next[index]; if(!p)p=root; node *temp=p; while(temp != root ) { if(temp->count>=0) { cnt+=temp->count; temp->count=-1; } else break; temp=temp->fail; } } return cnt;}
FAQ | About Virtual Judge | Forum | Discuss | Open Source Project
All Copyright Reserved ©2010-2012 HUST ACM/ICPC TEAM
Anything about the OJ, please ask in the forum, or contact author:Isun
Server Time: 0 0