hdu 2222 ac自动机模板题

题意

Sample Input
1
5
she
he
say
shr
her
yasherhs


Sample Output
3

 

  1 #include <stdio.h>
  2 #include <algorithm>
  3 #include <iostream>
  4 #include <string.h>
  5 #include <queue>
  6 using namespace std;
  7 struct Trie
  8 {
  9     int next[500010][26],fail[500010],end[500010];
 10     int root,L;
 11     int newnode()
 12     {
 13         for(int i = 0;i < 26;i++)
 14         next[L][i] = -1;
 15         end[L++] = 0;
 16         return L-1;
 17     }
 18     void init()
 19     {
 20         L = 0;
 21         root = newnode();
 22     }
 23     void insert(char buf[])
 24     {
 25         int len = strlen(buf);
 26         int now = root;
 27         for(int i = 0;i < len;i++)
 28         {
 29             if(next[now][buf[i]-'a'] == -1)
 30             next[now][buf[i]-'a'] = newnode();
 31             now = next[now][buf[i]-'a'];
 32         }
 33         end[now]++;
 34     }
 35     void build()
 36     {
 37         queue<int>Q;
 38         fail[root] = root;
 39         for(int i = 0;i < 26;i++)
 40         if(next[root][i] == -1)
 41         next[root][i] = root;
 42         else
 43         {
 44             fail[next[root][i]] = root;
 45             Q.push(next[root][i]);
 46         }
 47         while( !Q.empty() )
 48         {
 49             int now = Q.front();
 50             Q.pop();
 51             for(int i = 0;i < 26;i++)
 52             if(next[now][i] == -1)
 53             next[now][i] = next[fail[now]][i];
 54             else
 55             {
 56                 fail[next[now][i]]=next[fail[now]][i];
 57                 Q.push(next[now][i]);
 58             }
 59         }
 60     }
 61     int query(char buf[])
 62     {
 63         int len = strlen(buf);
 64         int now = root;
 65         int res = 0;
 66         for(int i = 0;i < len;i++)
 67         {
 68             now = next[now][buf[i]-'a'];
 69             int temp = now;
 70             while( temp != root )
 71             {
 72                 res += end[temp];
 73                 end[temp] = 0;
 74                 temp = fail[temp];
 75             }
 76         }
 77         return res;
 78     }
 79     void debug()
 80     {
 81         for(int i = 0;i < L;i++)
 82         {
 83             printf("id = %3d,fail = %3d,end = %3d,chi = [",i,fail[i],end[i]);
 84             for(int j = 0;j < 26;j++)
 85             printf("%2d",next[i][j]);
 86             printf("]\n");
 87         }
 88     }
 89 };
 90 char buf[1000010];
 91 Trie ac;
 92 int main()
 93 {
 94     int T;
 95     int n;
 96     scanf("%d",&T);
 97     while( T-- )
 98     {
 99         scanf("%d",&n);
100         ac.init();
101         for(int i = 0;i < n;i++)
102         {
103             scanf("%s",buf);
104             ac.insert(buf);
105         }
106         ac.build();
107         scanf("%s",buf);
108         printf("%d\n",ac.query(buf));
109     }
110     return 0;
111 }

 

posted @ 2015-04-20 16:33  miao_a_miao  阅读(147)  评论(0编辑  收藏  举报