Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 78393 Accepted Submission(s): 27259
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
#include <bits/stdc++.h>
using namespace std;
const int mn = 10010, mk = 55, md = 1000010;
int num;
int nx[mn * mk][30];
int ed[mn * mk], fail[mn * mk];
void init()
{
num = 0;
memset(nx, -1, sizeof nx);
memset(ed, 0, sizeof ed);
memset(fail, 0, sizeof fail);
}
void add(char ch[]) /// O(n * l)
{
int len = strlen(ch);
int now = 0;
for (int i = 0; i < len; i++)
{
if (nx[now][ch[i] - 'a'] == -1)
nx[now][ch[i] - 'a'] = ++num;
now = nx[now][ch[i] - 'a'];
}
ed[now]++; // 模式串可能重复
}
void build_Fail() /// O(n * l)
{ // BFS
queue<int>que;
int root = 0;
fail[root] = root;
for (int i = 0; i< 26; i++)
{
if (nx[root][i] == -1)
nx[root][i] = root;
else
{
fail[nx[root][i]] = root;
que.push(nx[root][i]);
}
}
while (!que.empty())
{
int now = que.front();
que.pop();
for (int i = 0; i < 26; i++)
{
if (nx[now][i] == -1)
nx[now][i] = nx[fail[now]][i];
else
{
fail[nx[now][i]] = nx[fail[now]][i];
que.push(nx[now][i]);
}
}
}
}
int ask(char ch[]) /// O(m * l)
{
int res = 0;
int len = strlen(ch);
int now = 0;
for (int i = 0; i < len; i++)
{
now = nx[now][ch[i] - 'a'];
int temp = now;
while (temp != 0)
{
res += ed[temp];
ed[temp] = 0; // 单次匹配
temp = fail[temp];
}
}
return res;
}
char ch2[md];
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
init();
int n;
scanf("%d", &n);
while (n--)
{
char ch[mk];
scanf("%s", ch);
add(ch); /// 构建模式串的字典树
}
build_Fail(); /// 创建失配指针
scanf("%s", ch2); /// 在此串中查找多个模式串
printf("%d\n", ask(ch2));
}
return 0;
}