HDU传送门
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 48409 Accepted Submission(s): 15436
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
Recommend
lcy
AC自动机模板题
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
#define N 1000050
char str[N],s[55];
struct AhoCorasick{
struct Node{
Node *fail,*next[26];int cnt;
Node(){for(int i=0;i<26;i++) next[i]=NULL;fail=NULL;cnt=0;}
}*root;
void insert(char *str){//建立Trie
int l;l=strlen(str);
Node *p=root;
for(int i=0,tmp=str[i]-'a';i<l;p=p->next[tmp],tmp=str[++i]-'a')
if(p->next[tmp]==NULL) p->next[tmp]=new Node();//没有该节点就新建一个
p->cnt++;//统计个数
}
void build(){//bfs计算fail失配
queue<Node*> q;q.push(root);//队列
while(!q.empty()){
Node *p=q.front(),*tmp=NULL;q.pop();//弹出队首
for(int i=0;i<26;i++){
if(p->next[i]!=NULL){
if(p!=root){
for(tmp=p->fail;tmp!=NULL;tmp=tmp->fail){
if(tmp->next[i]!=NULL)
{p->next[i]->fail=tmp->next[i];break;}//找到跳出循环
}
if(tmp==NULL) p->next[i]->fail=root;//没有匹配的指向root
}
else p->next[i]->fail=root;//第一个字符
q.push(p->next[i]);//加入队列
}
}
}
}
int query(){//计算匹配个数
int l=strlen(str),res=0;Node *p=root;
for(int i=0,ch=str[i]-'a';i<l;ch=str[++i]-'a'){
while(p->next[ch]==NULL&&p!=root) p=p->fail;//失配
p=p->next[ch];//查询字符
if(p==NULL) p=root;//重置
Node *tmp=p;
while(tmp!=root&&tmp->cnt!=-1)//累计
res+=tmp->cnt,tmp->cnt=-1,tmp=tmp->fail;
}
return res;
}
void init(){root=new Node();}//初始化
}ac;
int main(){
int t,n;scanf("%d",&t);
while(t--){
scanf("%d",&n);getchar();ac.init();
for(int i=1;i<=n;i++)
gets(s),ac.insert(s);
ac.build();scanf("%s",str);
printf("%d\n",ac.query());
}
return 0;
}