HDU 2222 Keywords Search

ac自动机模板题

链表写法:

  1 #include<iostream>
  2 #include<stdio.h>
  3 #include <string.h>
  4 using namespace std;
  5 
  6 #define T_size 1000000
  7 #define P_size 50
  8 #define Total_p 10000
  9 
 10 struct trie
 11 {
 12     trie *next[26];
 13     trie *fail;
 14     int num;
 15     trie()
 16     {
 17         for(int i=0; i<26; i++)
 18         {
 19             next[i]=NULL;
 20         }
 21         fail=NULL;
 22         num=0;
 23     }
 24 };
 25 
 26 char T[T_size+1];
 27 char P[P_size+1];
 28 trie* q[Total_p*P_size];
 29 
 30 void insert(trie *root,char *s)
 31 {
 32     trie*p=root;
 33     for(int i=0; s[i]!=''; i++)
 34     {
 35         if(p->next[s[i]-'a']==NULL)
 36             p->next[s[i]-'a']=new trie;
 37         p=p->next[s[i]-'a'];
 38     }
 39     p->num++;
 40 }
 41 
 42 void build_ac(trie* root)
 43 {
 44     int head=0,tail=0;
 45     q[tail++]=root;
 46     while(head!=tail)
 47     {
 48         trie* front=q[head++];
 49         for(int i=0; i<26; i++)
 50         {
 51             if(front->next[i]!=NULL)
 52             {
 53                 trie*p=front->fail;
 54                 while(p!=NULL)
 55                 {
 56                     if(p->next[i]!=NULL)
 57                     {
 58                         front->next[i]->fail=p->next[i];
 59                         break;
 60                     }
 61                     p=p->fail;
 62                 }
 63                 if(p==NULL)
 64                     front->next[i]->fail=root;
 65                 q[tail++]=front->next[i];
 66             }
 67         }
 68     }
 69 }
 70 
 71 int acfind(trie* root,char* T)
 72 {
 73     trie*p=root;
 74     int sum=0;
 75     for(int i=0,len=strlen(T); i<len; i++)
 76     {
 77         while(p->next[T[i]-'a']==NULL&&p!=root)
 78         {
 79             p=p->fail;
 80         }
 81         if(p->next[T[i]-'a']!=NULL)
 82            p=p->next[T[i]-'a'];
 83         trie*temp=p;
 84         while(temp!=root&&temp->num!=-1)
 85         {
 86             sum+=temp->num;
 87             temp->num=-1;
 88             temp=temp->fail;
 89         }
 90     }
 91     return sum;
 92 }
 93 
 94 int main()
 95 {
 96     int t;
 97     for(scanf("%d",&t); t>0; t--)
 98     {
 99         trie*root=new trie;
100         int n;
101         scanf("%d",&n);
102         getchar();
103         for(int i=0; i<n; i++)
104         {
105             gets(P);
106             insert(root,P);
107         }
108         build_ac(root);
109         gets(T);
110         printf("%d
",acfind(root,T));
111     }
112     return 0;
113 }
View Code

数组写法:

原文地址:https://www.cnblogs.com/ITUPC/p/5008956.html