C++——AC自动机例题——Keywords Search(HDU2222)

来源:互联网 发布:一元淘宝网怎么找 编辑:程序博客网 时间:2024/06/06 06:56

Keywords Search

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 58664    Accepted Submission(s): 19253


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



#include<iostream>#include<cstdio>#include<cstdlib>#include<algorithm>#include<cstring>#include<string>using namespace std;const int N=100000+3;const int M=1e6+3;const int L=50+3;int ttt,tot,n,vst[N*L];struct node{int cnt,fail;int trans[26];void init(){cnt=fail=0;memset(trans,0,sizeof(trans));}}tr[N*L];char s[M];void insert(char *s){int len=strlen(s);int u=1;for(int i=0;i<len;++i){if(!tr[u].trans[s[i]-'a'])tr[tr[u].trans[s[i]-'a']=++tot].init();u=tr[u].trans[s[i]-'a'];}++tr[u].cnt;}void buildFail(){static int qn,que[N*L];que[qn=1]=1;for(int ql=1;ql<=qn;++ql){int u=que[ql],v,w;for(int i=0;i<26;++i){v=tr[u].fail;while(!tr[v].trans[i]) v=tr[v].fail;v=tr[v].trans[i],w=tr[u].trans[i];if(w)tr[w].fail=v,que[++qn]=w;else tr[u].trans[i]=v;}}}int main(){for(int i=0;i<26;++i) tr[0].trans[i]=1;scanf("%d",&ttt);for(int tt=1;tt<=ttt;++tt){tr[tot=1].init();scanf("%d",&n);for(int i=1;i<=n;++i){scanf("%s",s);insert(s);}buildFail();scanf("%s",s);int len=strlen(s);int now=1,tmp,ans=0;for(int i=0;i<len;++i){now=tr[now].trans[s[i]-'a'];tmp=now;while(tmp&&vst[tmp]!=tt){vst[tmp]=tt;ans+=tr[tmp].cnt;tmp=tr[tmp].fail;}}printf("%d\n",ans);}return 0;}


0 0