hdu2222 Keywords Search【AC自动机】

时间:2022-09-02 14:07:50

Keywords Search

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

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   |   We have carefully selected several similar problems for you:  3065 2243 2825 3341 3247 

题意:

给定n个模式串和一个文本串,统计文本串中模式串的个数。

思路:

AC自动机模板。

多组数据一定要注意初始化!

 #include <iostream>
#include <set>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
//#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define inf 0x7f7f7f7f int t, n;
const int maxn = 5e5 + ;
const int maxlen = 1e6 + ; struct tree{
int fail;
int son[];
int ed;
}AC[maxlen];
int tot = ;
char s[maxlen]; void build(char s[])
{
int len = strlen(s);
int now = ;
for(int i = ; i < len; i++){
if(AC[now].son[s[i] - 'a'] == ){
AC[now].son[s[i] - 'a'] = ++tot;
}
now = AC[now].son[s[i] - 'a'];
}
AC[now].ed += ;
} void get_fail()
{
queue<int>que;
for(int i = ; i < ; i++){
if(AC[].son[i] != ){
AC[AC[].son[i]].fail = ;
que.push(AC[].son[i]);
}
}
while(!que.empty()){
int u = que.front();
que.pop();
for(int i = ; i < ; i++){
if(AC[u].son[i] != ){
AC[AC[u].son[i]].fail = AC[AC[u].fail].son[i];
que.push(AC[u].son[i]);
}
else{
AC[u].son[i] = AC[AC[u].fail].son[i];
}
}
}
} int AC_query(char s[])
{
int len = strlen(s);
int now = , ans = ;
for(int i = ; i < len; i++){
now = AC[now].son[s[i] - 'a'];
for(int t = now; t && AC[t].ed != -; t = AC[t].fail){
ans += AC[t].ed;
AC[t].ed = -;
}
}
return ans;
} int main()
{
scanf("%d", &t);
while(t--){
for(int i = ; i <= tot; i++){
AC[i].ed = ;
AC[i].fail = ;
for(int j = ; j < ; j++){
AC[i].son[j] = ;
}
}
tot = ;
scanf("%d", &n);
for(int i = ; i < n; i++){
scanf("%s", s);
build(s);
}
AC[].fail = ;
get_fail();
scanf("%s", s);
printf("%d\n", AC_query(s));
}
return ;
}