#10057. 「一本通 2.4 例 1」Keywords Search(AC自动机模板!!!)(一篇文章中有多少单词)

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值