HDU 2222(AC自动机)

本题考察AC自动机的应用,通过构建AC自动机,对于给定的一段描述和若干关键词,计算描述中匹配到的关键词数量。AC自动机在 Trie 树基础上增加 fail 指针,优化字符串匹配效率。解题思路包括理解 Trie 树、AC自动机的 fail 指针以及如何构建和利用 AC 自动机进行匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
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.

Input
First line will contain one integer means how many cases will follow by.
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.

Output
Print how many keywords are contained in the description.

Sample Input

1
5
she
he
say
shr
her
yasherhs

Sample Output

3

题目大意:给出n个单词,然后给出一段文本,问在文本中有多少个单词出现过。

解题思路:这是一道AC自动机的板子题,跑一遍AC自动机的板子就可以啦。

AC自动机主要是在trie树上加了一个fail指针匹配,如果一个单词的某一个后缀与另一个单词的前缀相等,那么该位置的fail指针指向相等的这一部分。
(因为AC自动机主要靠trie树的思想,其实指针失配很容易就看懂了,所以建议先理解trie树算法再来看AC自动机更好。emm ,如果可以,也可以再看一下KMP算法。)
比如该题中的样例:
在这里插入图片描述
上图就是我们得到的trie树,箭头表示fail指针指向(PS:因为没有不同颜色的笔,所以只画了这两个结点的fail指针的指向,其他的结点的fail指针都指向0)。我们可以看到she这个字符串和her这个字符串相比较,she的后缀等于he的前缀,因为有了这个fail指针,如果我们搜索到she,已经匹配到e这个字符的情况下,我们也相当于匹配到he这个字符串的所有字符,而在创建这个trie树时,he这条路径中e字符的结点已经有值了,即出现过,那么我们加上这个值就可以了,然后我们将her中的r加在she的后面,这样就可以继续匹配her这个字符串是否出现过啦。而我们得到fail树的方法一般是使用BFS,我们先将第一层的结点加入队列,然后再去寻找每一个结点的子节点,再加入队列,说起来,AC自动机的原理就是这样子啦。接下来看代码叭。
AC代码:

#pragma GCC optimize(2)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <bitset>
#include <queue>
//#include <random>
#include <time
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值