[HDU2222] Keywords Search

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

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

1 5 she he say shr her yasherhs

Sample Output

3
 
Recommend
lcy   |   We have carefully selected several similar problems for you:  2896 3065 2243 2825 3341
 

思路

AC自动机
构建trie树,加上fail指针,就是一个AC自动机了。

代码实现

 1 #include<cstdio>
 2 #include<cstring>
 3 const int size=3e5+1;
 4 const int maxl=1e6+1;
 5 int test,n,a,sz,ans;
 6 struct nate{int n[26],f,v;}t[size];
 7 char ch[maxl];
 8 void ins(){
 9     scanf("%s",ch);
10     for(int i=0,j=0;;i++){
11         if(!ch[i]){t[j].v++;break;}
12         a=ch[i]-'a';
13         if(!t[j].n[a]) t[j].n[a]=++sz;
14         j=t[j].n[a];
15     }
16 }
17 int q[size],head,tail;
18 void build(){
19     head=tail=0;
20     for(int i=0;i<26;i++) q[tail++]=t[0].n[i];
21     while(head<tail){
22         a=q[head++];
23         for(int i=0;i<26;i++)
24         if(t[a].n[i]){
25             int j=t[a].f;
26             while(!t[j].n[i]) j=t[j].f;
27             t[t[a].n[i]].f=t[j].n[i];
28             q[tail++]=t[a].n[i];
29         }
30     }
31 }
32 void match(){
33     scanf("%s",ch);
34     for(int i=0,j=0;ch[i];i++){
35         a=ch[i]-'a';
36         while(!t[j].n[a]) j=t[j].f;
37         j=t[j].n[a];
38         for(int k=j;t[k].v!=-1;k=t[k].f) ans+=t[k].v,t[k].v=-1;
39     }
40 }
41 int main(){
42     scanf("%d",&test);
43     while(test--){
44         scanf("%d",&n);
45         for(int i=0;i<26;i++) t[0].n[i]=++sz;
46         for(int i=1;i<=n;i++) ins();
47         build();
48         match();
49         printf("%d\n",ans);
50         ans=sz=0;
51         memset(t,0,sizeof(t));
52     }
53     return 0;
54 }

 

posted @ 2017-07-13 20:50  J_william  阅读(185)  评论(0编辑  收藏  举报