标签:
#include<iostream> #include<algorithm> using namespace std; struct node { node *fail; node *next[26]; int count; node(){ fail=NULL; count=0; memset(next,NULL,sizeof(next)); } }*q[50001]; struct stm { char str[205]; int cn; }; int head,tail; void insert(node *root,char str[]){ node *p=root; int index,i=0; while(str[i]){ index=str[i]-‘a‘; if(p->next[index]==NULL) p->next[index]=new node(); p=p->next[index]; i++; } p->count++; } /*建立失败指针,沿着该节点的父节点的失败指针走, */ void automation(node *root){ root->fail=NULL; q[head++]=root; while(head!=tail){ node *temp=q[tail++]; node *p=NULL; for(int i=0;i<26;i++){ if(temp->next[i]!=NULL){ if(temp==root) temp->next[i]->fail=NULL; 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 quary(node *root,char str[]){ node *p=root; int i=0,cnt=0,index; while(str[i]){ index=str[i]-‘a‘; while(p->next[index]==NULL&&p!=root) p=p->fail; p=p->next[index]; 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 n; stm s; node *root=new node(); while(cin>>n){ for(int i=1;i<=n;i++){ cin>>s.str; insert(root,s.str); s.cn=i; } } return 0; }
标签:
原文地址:http://www.cnblogs.com/wintersong/p/4575783.html