Keywords Search

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


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 题意:在一个目标串S中找多个模式串T出现的次数。 题解:AC自动机模板题。

飘过的小牛的AC自动机详细解答 ​​http://www.cppblog.com/menjitianya/archive/2014/07/10/207604.html​​ 英雄哪里出来的AC自动机详细解答

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1000005;
struct Node
{
Node *fail;
Node *next[26];
int cnt;
Node()
{
fail = NULL;
cnt = 0;
memset(next,NULL,sizeof(next));
}
};
char keyword[55];
char str[N];
void buildTrie(char *str,Node *root)
{
Node *p = root,*q;
int len = strlen(str);
for(int i=0; i<len; i++)
{
int idx = str[i]-'a';
if(p->next[idx]==NULL) p->next[idx]=new Node();
p = p->next[idx];
}
p->cnt++;
}
void build_AC_automation(Node *root)
{
queue<Node*> q;
root->fail = NULL;
q.push(root);
while(!q.empty())
{
Node *p = NULL;
Node *temp = q.front();
q.pop();
for(int i=0; i<26; i++)
{
if(temp->next[i]!=NULL)
{
if(temp==root) temp->next[i]->fail=root;
else
{
p=temp->fail;
while(p!=NULL)
{
if(p->next[i]!=NULL)
{
temp->next[i]->fail=p->next[i];
break;
}
p=p->fail;
}
if(p==NULL) temp->next[i]->fail=root;
}
q.push(temp->next[i]);
}
}
}
}
int query(char *str,Node *root)
{
int cnt = 0,len = strlen(str);
Node *p = root;
for(int i=0; i<len; i++)
{
int idx = str[i]-'a';
while(p->next[idx]==NULL&&p!=root)
{
p = p->fail;
}
p = p->next[idx];
p = (p==NULL)?root:p;
Node *temp = p;
while(temp!=root&&temp->cnt!=-1)
{
cnt+=temp->cnt;
temp->cnt = -1;
temp = temp->fail;
}
}
return cnt;
}
int main()
{
int tcase;
scanf("%d",&tcase);
while(tcase--)
{
int n;
scanf("%d",&n);
Node *root = new Node();
while(n--)
{
scanf("%s",keyword);
buildTrie(keyword,root);
}
build_AC_automation(root);
scanf("%s",str);
int ans = query(str,root);
printf("%d\n",ans);
}
return 0;
}