【HDU2222】Keywords Search AC自动机
【HDU2222】Keywords Search
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
Smple Output
3
题意:给出一堆单词和一个字符串,问有多少个单词在字符串中出现过。
题解:AC自动机第一道模板题,我没有用指针,结果也AC了。
#include <cstdio> #include <cstring> #include <iostream> #include <queue> using namespace std; struct node { int ch[26],fail,cnt; }p[250000]; int n,tot,len,ans; char str[1000010],w[60]; queue<int> q; void build() //构建fail指针 { int i,u,t; q.push(1); while(!q.empty()) { u=q.front(),q.pop(); for(i=0;i<26;i++) { if(!p[u].ch[i]) continue; q.push(p[u].ch[i]); if(u==1) { p[p[u].ch[i]].fail=1; continue; } t=p[u].fail; while(!p[t].ch[i]&&t) t=p[t].fail; if(t) p[p[u].ch[i]].fail=p[t].ch[i]; else p[p[u].ch[i]].fail=1; } } } void search() //查找 { int i,j,u,t; scanf("%s",str); len=strlen(str); u=1; ans=0; for(i=0;i<len;i++) { while(!p[u].ch[str[i]-'a']&&u!=1) u=p[u].fail; u=p[u].ch[str[i]-'a']; t=u=(u>0)?u:1; while(t!=1) { if(p[t].cnt>=0) ans+=p[t].cnt,p[t].cnt=-1; //防止重复计数 else break; t=p[t].fail; } } printf("%d\n",ans); } void work() { scanf("%d",&n); tot=1; memset(p,0,sizeof(p)); int i,j,k,t; for(i=1;i<=n;i++) { scanf("%s",w); k=strlen(w); t=1; for(j=0;j<k;j++) //构建Trie树 { if(!p[t].ch[w[j]-'a']) p[t].ch[w[j]-'a']=++tot; t=p[t].ch[w[j]-'a']; } p[t].cnt++; } build(); search(); } int main() { int T; scanf("%d",&T); while(T--) work(); return 0; }
| 欢迎来原网站坐坐! >原文链接<