hdu 2222


AC自动机

http://www.cnblogs.com/kuangbin/p/3164106.html
next[ ]高端实现方法,膜拜不已~



#include<map>
#include<string>
#include<queue>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>

const int MAXN =  10005, MAXL = 55, MAXS = 1000005;

int n;
struct TireNode{TireNode *p[26],*fail; int end;}*root = 0, *p , emp = {{NULL},NULL,0};
std::queue<TireNode*>line;

TireNode *newnode(){TireNode *ret = (TireNode*)malloc(sizeof(TireNode)); (*ret) = emp; return ret;}

inline void TireBuild() 
{  
    static char s[MAXL] = {'\0'};
    TireNode *tmp;int sl = 0;

    root = newnode(); 
    for(int i = 1; i <= n; i++)
    {
        tmp = root;
        scanf("%s",s); sl = strlen(s);
        for(int j = 0; j < sl; j++)
        {
            if(!tmp->p[s[j]-'a'])
              tmp->p[s[j]-'a'] = newnode();
            tmp = tmp->p[s[j]-'a'];   
        }
        tmp->end++;
    }
}
inline void acBuild()
{   
    root->fail = root;
    for(int i = 0; i < 26; i++)
      if(!root->p[i])root->p[i] = root;
      else  
      { 
       root->p[i]->fail = root;
       line.push(root->p[i]); 
      }

    while(!line.empty())
    {
        TireNode *now = line.front();
        line.pop();
        for(int i = 0; i < 26;i++)
          if(!now->p[i])
            now->p[i] = now->fail->p[i];
          else
          { 
            now->p[i]->fail = now->fail->p[i];
            line.push(now->p[i]);
          }
    }
}
inline int query(char str[])
{
    int ret = 0,len = strlen(str);
    TireNode *now = root, *tmp;

    for(int i = 0 ;i < len ;i++)
    {
       now = now->p[str[i]-'a'];

       tmp = now;
       while(tmp != root && tmp->end != -1)
       {
          ret += tmp->end;
          tmp->end = -1;
          tmp = tmp ->fail;
       }
    }

    return ret;
}
int main()
{
    int T;
#ifndef ONLINE_JUDGE
    freopen("hdu2222.in","r",stdin);
    freopen("hdu2222.out","w",stdout);
#endif

    scanf("%d",&T);
    while(T--)
    {
        static char mus[MAXS] = {'\0'};

        scanf("%d",&n);

        TireBuild();
        acBuild();

        scanf("%s",mus);
        printf("%d\n",query(mus));

    }
#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

你可能感兴趣的:(hdu)