AC自动机模板(HDU - 2222)

题目描述
给定 n 个长度不超过 50 的由小写英文字母组成的单词准备查询,以及一篇长为 m 的文章,问:文中出现了多少个待查询的单词。多组数据。

输入格式
第一行一个整数 T,表示数据组数;

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

输出格式
对于每组数据,输出一个数,表示文中出现了多少个待查询的单词。

输入样例

1
5
she
he
say
shr
her
yasherhs

输出样例

3

数据范围
对于全部数据, 1 ≤ n ≤ 1 0 4 , 1 ≤ m ≤ 1 0 6 1≤n≤10^4,1≤m≤10^6 1n104,1m106

`​#include <bits/stdc++.h>

using namespace std;

const int N = 5e5 + 10;

struct Trie
{
	int next[N][26], fail[N], end[N]; // next表明下一次向哪儿走, fail[x] 表明如果失配,向那个点转移
	int root, idx;
	int newnode()
	{
		for(int i = 0; i < 26; i ++) next[idx][i] = -1;
		end[idx ++] = 0;
		return idx - 1;
	}
	void init()
	{
		idx = 0;
		root = newnode();
	}
	void insert(char buf[]) // 字典树基本操作
	{
		int len = strlen(buf);
		int now = root;
		for(int i = 0; i < len; i ++)
		{
			int v = buf[i] - 'a';
			if(next[now][v] == -1)
			{
				next[now][v] = newnode();
			}
			now = next[now][v];
		}
		end[now] ++;
	}

	void build() // 核心函数
	{
		queue<int> q;
		fail[root] = root;
		for(int i = 0; i < 26; i ++) // 处理第一层字典树
		{
			int &tmp = next[root][i];
			if(tmp == -1)
			{
				tmp = root; // 下个节点设为根
			}
			else
			{
				fail[tmp] = root; // fail返回根节点,也标志这查询结束
				q.push(tmp);
			}
		}
		while(!q.empty()) // 类似dp记录状态转移
		{
			int now = q.front();
			q.pop();
			for(int i = 0; i < 26; i ++)
			{
				int &tmp = next[now][i]; // 子点
				if(tmp == -1)
				{
					tmp = next[fail[now]][i]; // 如果到了叶子节点, next数组就以该叶子节点失配处理
				}
				else
				{
					fail[tmp] = next[fail[now]][i];
					q.push(tmp);
				}
			}
			// 一个可选的选择是 end[now] += end[fail[now]]
			// 此时的end[now] 就记录的是以now结尾的字符串和其某个后缀相同的字符串数量
			//在查询时就不需要循环了
		}

	}

	int query(char buf[])
	{
		int len = strlen(buf);
		int now = root;
		int res = 0;
		for(int i = 0; i < len; i++)
		{
			now = next[now][buf[i] - 'a'];
			int temp = now;
			while(temp != root) // 含第i个字母为结尾的一次匹配
			{
				res += end[temp];
				end[temp] = 0;
				temp = fail[temp];
			}
		}
		return res;
	}

	void debug()
	{
		for(int i = 0; i < idx; i++)
		{
			printf("id = %3d,fail = %3d,end = %3d,chi = [",i,fail[i],end[i]);
			for(int j = 0; j < 26; j++)
				printf("%2d", next[i][j]);
			printf("]\n");
		}
	}
} ac;

char buf[N<<1];
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int T, n;
	cin >> T;
	while(T --)
	{
		cin >> n;
		ac.init();
		for(int i = 1; i <= n; i++)
		{
			cin >> buf;
			ac.insert(buf);
		}
		ac.build();
		cin >> buf;
		cout << ac.query(buf) << endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值