hdu 2222(AC自动机入门题)

来源:互联网 发布:c语言调用shell命令 编辑:程序博客网 时间:2024/05/29 08:18

Keywords Search

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11021    Accepted Submission(s): 3834


Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.
 

Input
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.
 

Output
Print how many keywords are contained in the description.
 

Sample Input
15shehesayshrheryasherhs
 

Sample Output
3
 

Author
Wiskey
 

Recommend
lcy
 
题目:http://acm.hdu.edu.cn/showproblem.php?pid=2222
分析:AC自动机入门题,不会算法的自己网上找吧~~~
代码:
#include<cstdio>#include<cstring>#define mm 88888#define mn 55#define N 26int tire[mm][N];int fail[mm],w[mm],Q[mm];int cg[128];int size;char tmp[mn],s[1111111];void build(char *word){    int i=0,j;    for(;*word;++word,i=tire[i][j])        if(!tire[i][j=cg[*word]])        {            memset(tire[size],0,sizeof(tire[size]));            w[tire[i][j]=size++]=0;        }    ++w[i];}void AC(){    int *l=Q,*r=Q,i,j,k;    for(i=0;i<N;++i)        if(tire[0][i])fail[*r++=tire[0][i]]=0;    for(;l!=r;++l)        for(i=*l,j=0;j<N;++j)            if(k=tire[i][j])fail[*r++=k]=tire[fail[i]][j];            else tire[i][j]=tire[fail[i]][j];}int main(){    int i,j,r,n,T,ans;    for(fail[0]=i=0; i<26; ++i)cg[i+'a']=i;    scanf("%d",&T);    while(T--)    {        memset(tire[0],0,sizeof(tire[0]));        size=1;        scanf("%d",&n),getchar();        while(n--)gets(tmp),build(tmp);        AC();        gets(s);        ans=i=r=0;        while(s[r])        {            j=i=tire[i][cg[s[r++]]];            while(j&&w[j]!=-1)                ans+=w[j],w[j]=-1,j=fail[j];        }        printf("%d\n",ans);    }    return 0;}