hdu-3065 病毒侵袭持续中 --------AC自动机
题意:给出m个模式和一个文本,求各种模式的出现次数
比较裸的AC自动机,成功匹配就计数就是了..
View Code
1 //Accepted 3065 281MS 13724K 2340 B C++ 2 3 #include <iostream> 4 #include <cstring> 5 #include <cstdio> 6 #include <cmath> 7 #include <algorithm> 8 using namespace std; 9 const int inf=1<<28; 10 const int nMax=1010; 11 const int mMax=100010; 12 int vis[nMax]; 13 class node{ 14 public: 15 int id; 16 node *next[100],*fail; 17 node(){ 18 id=0; 19 fail=NULL; 20 memset(next,0,sizeof(next)); 21 } 22 }*root,*que[mMax]; 23 char P[1010][55]; 24 char T[2000010]; 25 26 void insert(char *s,int id){ 27 int i; 28 node *r=root; 29 int l=strlen(s); 30 for(i=0;i<l;i++){ 31 int loc=s[i]-30; 32 if(r->next[loc]==NULL){ 33 r->next[loc]=new node(); 34 } 35 r=r->next[loc]; 36 } 37 r->id = id; 38 } 39 40 void acAuto(){ //用bfs为每个节点设定fail指针 41 int i,head=0,tail=0; 42 node *p,*tmp; 43 root->fail=NULL; 44 que[tail++]=root; 45 while(head<tail) 46 { 47 tmp=que[head++]; 48 for(i=0;i<100;i++){ 49 if(tmp->next[i]==NULL)continue; 50 if(tmp==root){ 51 tmp->next[i]->fail=root; 52 } 53 else { 54 for(p=tmp->fail;p!=NULL;p=p->fail){ 55 if(p->next[i]!=NULL){ 56 tmp->next[i]->fail=p->next[i]; 57 break; 58 } 59 } 60 if(p==NULL){ 61 tmp->next[i]->fail=root; 62 } 63 } 64 que[tail++]=tmp->next[i]; 65 } 66 } 67 } 68 69 70 void search(char msg[]) 71 { 72 int i,idx,ans=0; 73 node *p=root,*tmp; 74 for(i=0;msg[i];i++) 75 { 76 idx=msg[i]-30; 77 while(p->next[idx]==NULL&&p!=root) 78 { 79 p=p->fail; 80 } 81 if(p->next[idx]) 82 p=p->next[idx]; 83 84 for(tmp=p;tmp!=root;tmp=tmp->fail) 85 { 86 vis[tmp->id]++; 87 } 88 } 89 } 90 91 void freedom(node *p) 92 { 93 int i=0; 94 for(i=0;i<100;i++) 95 if(p->next[i]!=NULL) 96 freedom(p->next[i]); 97 free(p); 98 } 99 100 101 int main(void) 102 { 103 int i,n; 104 105 root=new node(); 106 while(scanf("%d",&n)!=EOF) 107 { 108 for(i=1;i<=n;i++) 109 { 110 scanf("%s",P[i]); 111 insert(P[i],i); 112 } 113 acAuto(); 114 memset(vis,0,sizeof(vis)); 115 scanf("%s",T); 116 search(T); 117 for(i=1; i<=n; i++) 118 if(vis[i]) 119 printf("%s: %d\n",P[i],vis[i]); 120 freedom(root); 121 root = new node(); 122 } 123 return 0; 124 }


浙公网安备 33010602011771号