Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 63350 Accepted Submission(s): 21015
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.
題目大意:
給n 個字母,以及一個串,問這個串中有多少個字母,不能重複計數
題目思路:
AC自動機模板,對於AC自動機的講解可以看這篇博文:ac自動機詳解
AC代碼:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
const int maxn = 1e6+10;
const int maxtot = 5e5+10;
int Size;
struct Tree
{
int nex[26];
int fail,cnt;
void init()
{
fail = cnt = 0;
memset(nex,0,sizeof(nex));
}
}node[maxtot];
void Insert(char *s)
{
int n = strlen(s);
int now = 0;
for(int i=0;i<n;i++)
{
int id = s[i]-'a';
if(!node[now].nex[id])
{
node[now].nex[id] = Size++;
}
now = node[now].nex[id];
}
node[now].cnt++;
}
queue<int>q;
void Build()
{
node[0].fail = -1;
q.push(0);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i=0;i<26;i++)
{
if(node[u].nex[i])
{
if(u==0)node[node[u].nex[i]].fail = 0;
else
{
int v = node[u].fail ;
while(v!=-1)
{
if(node[v].nex[i])
{
node[node[u].nex[i]].fail = node[v].nex[i];
break;
}
v = node[v].fail;
}
if(v==-1)node[node[u].nex[i]].fail = 0;
}
q.push(node[u].nex[i]);
}
}
}
}
int Search(char *s)
{
int n = strlen(s);
int res = 0,now = 0;
for(int i=0;i<n;i++)
{
int id = s[i]-'a';
if(node[now].nex[id])now = node[now].nex[id];
else
{
int p = node[now].fail;
while(p!=-1&&node[p].nex[id]==0)p = node[p].fail;
if(p==-1)now = 0;
else now = node[p].nex[id];
}
if(node[now].cnt)
{
int uu = now;
while(uu)
{
res+=node[uu].cnt;
node[uu].cnt = 0;
uu = node[uu].fail;
}
}
}
return res;
}
void init()
{
for(int i=0;i<maxtot;i++)
node[i].init();
Size = 1;
}
char s[maxn];
int main()
{
int t;cin>>t;
while(t--)
{
int n;
scanf("%d",&n);
init();
for(int i=0;i<n;i++)
{
scanf("%s",s);
Insert(s);
}
Build();
scanf("%s",s);
printf("%d\n",Search(s));
}
return 0;
}