HDU 2222 Keywords Search AC自动机

题意:给定n个关键字,每个关键字为一个单词,和一个长字符串,求字符串中包含的关键字数量
思路:AC自动机模版题
主要就是在Trie树的基础上加上了一个fail指针,fail指针指向包含最长相同后缀的根节点的另一子节点,字符串匹配过程中当前字符失配时,转向fail指针指向的节点继续匹配。
fail指针的建立:
首先每个单词第一个字母的fail指针肯定是根节点,子节点的fail指针用bfs搜索整棵Trie树,每次搜索当前节点都从26个字母中对当前节点进行匹配:
若字母不等于当前节点,则父亲节点孩子中对应字母节点变为父亲节点fail指针指向的节点的孩子中的当前字母节点;若字母等于当前节点,则将当前节点的fail指针指向父亲的fail指针指向的节点的孩子中具有相同字母的节点。
匹配过程:
首先沿着Trie树向下找,若当前为单词,ans++,若当前单词没有子节点,就从当前单词的fail指针的子节点开始继续找,如果fail指针为根,而从根再也找不到下一个字符,匹配结束

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const int inf = 0x3f3f3f3f;
int ch[maxn][26], cntword[maxn], fail[maxn], cnt, T, n;
char s[maxn];
void insert(string s)
{
	int p = 0;
	for (int i = 0; i < s.length(); i++) {
		int next = s[i] - 'a';
		if (!ch[p][next])
			ch[p][next] = ++cnt;
		p = ch[p][next];
	}
	cntword[p]++;
}
void build()
{
	queue<int> q;
	for (int i = 0; i < 26; i++) {
		if (ch[0][i]) {
			fail[ch[0][i]] = 0;
			q.push(ch[0][i]);
		}
	}
	while (!q.empty()) {
		int now = q.front(); q.pop();
		for (int i = 0; i < 26; i++) {
			if (ch[now][i]) {
				fail[ch[now][i]] = ch[fail[now]][i];
				q.push(ch[now][i]);
			}
			else
				ch[now][i] = ch[fail[now]][i];
		}
	}
}
int query(string s)
{
	int now = 0, ans = 0;
	for (int i = 0; i < s.length(); i++) {
		now = ch[now][s[i]-'a'];
		for (int j = now; j && cntword[j] != -1; j = fail[j]) {
			ans += cntword[j];
			cntword[j] = -1;
		}
	}
	return ans;
}
int main()
{
	scanf("%d", &T);
	for (int t = 0; t < T; t++) {
		scanf("%d", &n);
		memset(ch, 0, sizeof(ch));
		memset(fail, 0, sizeof(fail));
		memset(cntword, 0, sizeof(cntword));
		for (int i = 0; i < n; i++) {
			scanf("%s", s);
			insert(s);
		}
		fail[0] = 0;
		build();
		scanf("%s", s);
		printf("%d\n", query(s));
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值