SSL 1904.搜索关键词 AC自动机

题目描述

  给定 n 个长度不超过 50 的由小写英文字母组成的单词,以及一篇长为 m 的文章。

  请问,其中有多少个单词在文章中出现了。

  注意:每个单词不论在文章中出现多少次,仅累计 1 次。

输入

第一行包含整数 T,表示共有 T 组测试数据。

对于每组数据,第一行一个整数 n,接下去 n 行表示 n 个单词,最后一行输入一个字符串,表示文章。

输出

对于每组数据,输出一个占一行的整数,表示有多少个单词在文章中出现。

输入样例 复制

1
5
she
he
say
shr
her
yasherhs

输出样例 复制

3
#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)
{
	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];
			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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值