Keywords Search
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/131072K (Java/Other)
Total Submission(s) : 20 Accepted Submission(s) : 17
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
解題思路:使用AC自動機模板
AC代碼:
#include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
#include<queue>
using namespace std;
struct Trie
{
int values;
Trie *child[26];
Trie *fail;
Trie()
{
values=0;
memset(child,NULL,sizeof(child));
fail=NULL;
}
}*root;
int ans;
char patten[60];
char text[1000010];
void create(char s[]) //構建字典樹
{
Trie *x=root;
for(int i=0;i<strlen(s);i++)
{
int d=s[i]-'a';
if(x->child[d]==NULL)
{
x->child[d]=new Trie;
}
x=x->child[d];
}
x->values++;
}
void deleteTrie(Trie *x) //清除字典樹
{
if(x==NULL)
return;
for(int i=0;i<26;i++)
{
if(x->child[i]!=NULL)
{
deleteTrie(x->child[i]);
}
}
delete x;
}
void build_AC_automaton() //構建AC自動機
{
Trie *p;
p=root;
queue<Trie*> qu; //使用廣搜實現
qu.push(p);
while(!qu.empty())
{
p=qu.front();
qu.pop();
for(int i=0;i<26;i++)
{
if(p->child[i]!=NULL)
{
if(p==root)
{
p->child[i]->fail=root;
}
else
{
Trie *node=p->fail;
while(node!=NULL) //查找當前節點的fail指針是否爲空
{
if(node->child[i]!=NULL) //判斷當前節點和fail指針指向的孩子節點是否相等
{
p->child[i]->fail=node->child[i]; //相等令p的孩子節點fail指針指向p節點指向的fail指針的孩子節點
break;
}
node=node->fail;
}
if(node==NULL)
p->child[i]->fail=root;
}
qu.push(p->child[i]);
}
}
}
}
void find_in_AC_automaton() //查找過程
{
Trie *p;
p=root;
int index=0;
while(text[index]!='\0')
{
int id=text[index]-'a';
while(p->child[id]==NULL && p!=root)
p=p->fail;
p=p->child[id];
if(p==NULL) p=root;
Trie *temp=p;
while(temp!=NULL && temp->values!=-1)
{
ans+=temp->values;
temp->values=-1;
temp=temp->fail;
}
index++;
}
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
root = new Trie;
for(int i=0;i<n;i++)
{
scanf("%s",patten);
create(patten);
}
scanf("%s",text);
build_AC_automaton();
ans=0;
find_in_AC_automaton();
printf("%d\n",ans);
deleteTrie(root);
}
return 0;
}