Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 40636 Accepted Submission(s): 12942
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.
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.
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define maxn 500010
struct Trie
{
int next[maxn][26], fail[maxn], endd[maxn];
int root, L;
int newnode()
{
for(int i=0; i<26; i++)
next[L][i]=-1;
endd[L++]=0;
return L-1;
}
void init()
{
L=0;
root=newnode();
}
void insert(char *buf)
{
int len=strlen(buf);
int now=root;
for(int i=0; i<len ; i++){
if(next[now][buf[i]-'a']==-1)
next[now][buf[i]-'a']=newnode();
now=next[now][buf[i]-'a'];
}
endd[now]++;
}
void build()
{
queue<int> que;
fail[root]=root;
for(int i=0; i<26; i++)
if(next[root][i]==-1)
next[root][i]=root;
else{
fail[next[root][i]]=root;
que.push(next[root][i]);
}
while(!que.empty()){
int now=que.front(); que.pop();
for(int i=0; i<26; i++)
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else{
fail[next[now][i]]=next[fail[now]][i];
que.push(next[now][i]);
}
}
}
int query(char *buf)
{
int len=strlen(buf);
int now=root;
int res=0;
for(int i=0; i<len; i++){
now=next[now][buf[i]-'a'];
int temp=now;
while(temp!=root){
res+=endd[temp];
endd[temp]=0;
temp=fail[temp];
}
}
return res;
}
};
char buf[maxn<<1];
Trie trie;
int main()
{
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
trie.init();
for(int i=0; i<n; i++){
scanf("%s", buf);
trie.insert(buf);
}
trie.build();
scanf("%s", buf);
int ans=trie.query(buf);
printf("%d\n", ans);
}
return 0;
}