Keywords Search
题目链接:https://loj.ac/problem/10057
题目描述
给定 n 个长度不超过 50 的由小写英文字母组成的单词准备查询,以及一篇长为 m 的文章,问:文中出现了多少个待查询的单词。多组数据。
输入格式
第一行一个整数 T,表示数据组数;
对于每组数据,第一行一个整数 n,接下去 n 行表示 n 个单词,最后一行输入一个字符串,表示文章。
输出格式
对于每组数据,输出一个数,表示文中出现了多少个待查询的单词。
样例输入:
1
5
she
he
say
shr
her
yasherhs
样例输出:
3
数据范围与提示:
对于全部数据1<=n<=10^4
1<=m<=10^6
可以参考:https://www.cnblogs.com/hyfhaha/p/10802604.html
https://www.cnblogs.com/hyfhaha/p/10802604.html
AC代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int N=5e5+5;
int ans,cnt,nxt[N],ch[N][30],bo[N],que[N];
void make(char *s)//建立Trie数
{
int u=1,len=strlen(s),i;
for(i=0; i<len; i++)
{
int c=s[i]-'a';
if(!ch[u][c])
ch[u][c]=++cnt;
u=ch[u][c];
}
bo[u]++;
return ;
}
void bfs()//
{
que[1]=1,nxt[1]=0;
int head,tail,i;
for(head=1,tail=1; head<=tail; head++)
{
int u=que[head];
for(i=0; i<=25; i++)
{
if(!ch[u][i])//如果这个点没有找到
ch[u][i]=ch[nxt[u]][i];//nxt[u]是父亲结点的失败指针
else//如果找到这个点
{
que[++tail]=ch[u][i];//先把这个点加入队列
//该点的失败指针就是它父亲节点失败指针节点的儿子节点
nxt[ch[u][i]]=ch[nxt[u]][i];
}
}
}
}
void find(char *s)
{
int u=1,len=strlen(s),c,k,i;
for(i=0; i<len; i++)
{
c=s[i]-'a';
k=ch[u][c];
while(k>1)
{
ans+=bo[k];
bo[k]=0;
k=nxt[k];
}
u=ch[u][c];
}
return ;
}
int main()
{
int t,n;
char s[N<<1];
scanf("%d",&t);
while(t--)
{
ans=0,cnt=1;
memset(bo,0,sizeof(bo));
memset(ch,0,sizeof(ch));
for(int i=0; i<26; i++)
{
ch[0][i]=1;
ch[1][i]=0;
}
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%s",s);
make(s);
}
bfs();
scanf("%s",s);
find(s);
printf("%d\n",ans);
}
return 0;
}