Keywords SearchTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 64736 Accepted Submission(s): 21585
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
Sample Output
Author
Wiskey
Recommend
lcy
|
题意:给出n个串,然后给一篇文章,问这n个串有多少个在文章里面出现过。。。
trick:n个串可能有相同的,需按照不同串处理。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 1e6 + 7;
const int maxnode = 50*10010;
int n;
char s1[60], s2[maxn];
struct node
{
int ch[maxnode][26], cnt[maxnode], fail[maxnode], last[maxnode], id, road[maxnode]; // 路径压缩优化, 针对模式串出线的种类
void init()
{
memset(ch[0], 0, sizeof(ch[0]));
id = 1;
}
void Insert(char *s)
{
int rt = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(!ch[rt][s[i]-'a'])
{
memset(ch[id], 0, sizeof(ch[id]));
cnt[id] = 0;
ch[rt][s[i]-'a'] = id++;
}
road[ch[rt][s[i]-'a']] = 1;
rt = ch[rt][s[i]-'a'];
}
cnt[rt]++;
}
void get_fail()
{
queue<int> q;
fail[0] = 0;
int rt = 0;
for(int i = 0; i < 26; i++)
{
rt = ch[0][i];
if(rt)
{
q.push(rt);
fail[rt] = 0;
last[rt] = 0;
}
}
while(!q.empty())
{
int r = q.front();
q.pop();
for(int i = 0; i < 26; i++)
{
rt = ch[r][i];
if(!rt)
{
ch[r][i] = ch[fail[r]][i];
continue;
}
q.push(rt);
int to = fail[r];
while(to && !ch[to][i])
to = fail[to];
fail[rt] = ch[to][i];
last[rt] = cnt[fail[rt]] ? fail[rt] : last[fail[rt]];
}
}
}
int Find(char *s)
{
int rt = 0, res = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
rt = ch[rt][s[i]-'a'];
int temp = 0;
if(cnt[rt])
temp = rt;
else if(last[rt])
temp = last[rt];
while(temp)
{
res += cnt[temp];
cnt[temp] = 0;
temp = last[temp];
}
}
return res;
}
}ac_auto;
int main()
{
int t;
cin >> t;
while(t--)
{
scanf("%d", &n);
ac_auto.init();
for(int i = 1; i <= n; i++)
{
scanf("%s", s1);
ac_auto.Insert(s1);
}
ac_auto.get_fail();
scanf("%s", s2);
printf("%d\n", ac_auto.Find(s2));
}
return 0;
}