AC自动机初步入门详解

前言

AC自动机(Aho-Corasick automaton)是KMP的升级版。KMP是单模匹配算法,处理在一个文本串中查找一个模式串的问题;AC自动机是多模匹配算法,能在一个文本串中同时查找多个不同的模式串。

多模块匹配问题:给定一个长度为n的文本S,以及k个平均长度为m的模式串P1,P2,…,Pn,要求搜索这些模式串出现的位置。
其实用KMP也能解决多模匹配问题,缺点是复杂度较高,需要对每个P1,P2,…,Pn,分别做一次KMP,总复杂度是O((n+m)k)。

AC自动机算法并不需要对S做多次KMP,而是只搜索一遍S,在搜索时匹配所有的模式串。

如何同时匹配所有的P?如果我们结合字典树的恍然大悟了。

KMP是通过查找P对应的Next[ ],数组实现快速匹配的。如果把所有的P做成一个字典树,然后在匹配的时候查找这个P对应的Next[ ]数组,不就实现了快速匹配的效果吗?

复杂度分析:k个模式串,平均长度为m;文本串长度为n。建立字典树O(km);建立fail指针O(km);模式匹配O(nm),乘m的原因是在统计的时候需要顺着链回溯到root节点。总时间复杂度是O(km+km+nm) = O(km+nm)。

对比简单的使用KMP的复杂度O((n+m)k),当m<<k时,(k+n)m<<(n+m)k。AC自动机优势非常大。

题解

HDU 2222 “Keywords Search”

题目传送门

Keywords Search

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 87399 Accepted Submission(s): 30405

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值