Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 81386 Accepted Submission(s): 28398 Problem Description In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Input First line will contain one integer means how many cases will follow by.
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
|
这个题目的话,弄成模板存一下
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int maxnode=500000+100;
const int sigma_size=26;
int ans;
struct AC_Automata
{
int ch[maxnode][sigma_size];
int val[maxnode];
int f[maxnode];
int last[maxnode];
bool vis[maxnode];
int sz;
void init()
{
sz=1;
memset(ch[0],0,sizeof(ch[0]));
vis[0]=false;
last[0]=f[0]=val[0]=0;
}
void insert(char *s)
{
int n=strlen(s),u=0;
for(int i=0;i<n;i++)
{
int id=s[i]-'a';
if(ch[u][id]==0)
{
vis[sz]=false;
ch[u][id]=sz;
memset(ch[sz],0,sizeof(ch[sz]));
val[sz++]=0;
}
u=ch[u][id];
}
vis[u]=true;
val[u]++;
}
void print(int i)
{
if(val[i])
{
if(vis[i])
{
ans+=val[i];
vis[i]=false;
}
print(last[i]);
}
}
void find(char *s)
{
int n=strlen(s),j=0;
for(int i=0;i<n;i++)
{
int id=s[i]-'a';
while(j && ch[j][id]==0) j=f[j];
j=ch[j][id];
if(val[j]) print(j);
else if(last[j]) print(last[j]);
}
}
void getFail()
{
queue<int> q;
f[0]=0;
for(int i=0;i<sigma_size;i++)
{
int u=ch[0][i];
if(u)
{
last[u]=f[u]=0;
q.push(u);
}
}
while(!q.empty())
{
int r=q.front();q.pop();
for(int i=0;i<sigma_size;i++)
{
int u=ch[r][i];
if(!u) continue;
q.push(u);
int v=f[r];
while(v && ch[v][i]==0) v=f[v];
f[u]=ch[v][i];
last[u] = val[f[u]]?f[u]:last[f[u]];
}
}
}
}ac;
const int MAXN=1000000+10;
char text[MAXN],word[100];
int main()
{
int t;scanf("%d",&t);
while(t--)
{
ans=0;
ac.init();
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%s",word);
ac.insert(word);
}
ac.getFail();
scanf("%s",text);
ac.find(text);
cout<<ans<<endl;
}
}