hdu----(2222)Keywords Search(ac自动机)

时间:2022-06-23 21:25:20

Keywords Search

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

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
 
Author
Wiskey
 
ac自动机:  构造一颗Trie树,像kmp一样构造一个失败指针,进行记录;
代码:
 #define LOCAL
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
struct Trie
{
struct Trie *fail;
struct Trie *child[];
int tail; //末尾标记
}; void _insert(char *s,Trie *root) //构造一个Trie树
{
Trie *newcur,*cur;
cur=root;
for(int i=;s[i];i++)
{
if(cur->child[s[i]-'a']==NULL)
{
newcur= new Trie ;
for(int j=;j<;j++)
newcur->child[j]=NULL;
newcur->fail=NULL;
newcur->tail=;
cur->child[s[i]-'a']=newcur;
}
cur=cur->child[s[i]-'a'];
}
cur->tail++; //有可能有重复的单词
} //构造失败指针
void ac_fail(Trie * root)
{
queue<Trie*>tree;
Trie *fro,*q;
tree.push(root);
while(!tree.empty())
{
fro=tree.front();
tree.pop();
for(int i=;i<;i++){
if(fro->child[i]!=NULL)
{
if(fro==root)
fro->child[i]->fail=root; //将他的下一个函数的指针的失败指针指向当前指针
else
{
q=fro;
while(q->fail)
{
if(q->fail->child[i]){
fro->child[i]->fail=q->fail->child[i];
break;
}
q=q->fail;
}
if(!q->fail) fro->child[i]->fail=root;
}
tree.push(fro->child[i]);
}
}
}
} int query(char *s,Trie *root)
{
Trie *cur=root,*newcur;
int ans=;
for(int i=;s[i];i++)
{
while(cur->child[s[i]-'a']==NULL&&cur!=root)
cur=cur->fail;
cur=cur->child[s[i]-'a'];
if(cur==NULL) cur=root;
newcur=cur;
while(newcur!=root&&newcur->tail>)
{
ans+=newcur->tail;
newcur->tail=;
newcur=newcur->fail;
}
}
return ans;
}
char s1[];
char t1[]; //目标主串
int main()
{
#ifdef LOCAL
freopen("test.in","r",stdin);
#endif
int cas,n;
Trie *root;
scanf("%d",&cas);
while(cas--)
{
scanf("%d",&n);
root= new Trie;
for(int i=;i<;i++)
root->child[i]=NULL;
root->fail=NULL;
root->tail=;
while(n--)
{
scanf("%s",s1);
_insert(s1,root);
}
ac_fail(root);
scanf("%s",t1);
printf("%d\n",query(t1,root));
}
return ;
}