AcWing 1282. 搜索关键词 题解((AC自动机)Trie+KMP)+bfs)

AcWing 1282. 搜索关键词((AC自动机)Trie+KMP)+bfs)
很早就想学的一个算法,不过以前是真听不懂,好在这次听懂了
希望AC自动机能帮我AC吧
请添加图片描述

#include<bits/stdc++.h>

using namespace std;

const int N = 1e4 + 10, S = 55;

int cnt[N * S], tr[N * S][26], ne[N * S];
int n, T, ids;
int q[N * S];
string str;

void insert(){
	int p = 0;
	for(int i = 0; str[i]; i ++ ){
		int t = str[i] - 'a';
		if(!tr[p][t]) tr[p][t] = ++ ids;
		p = tr[p][t];
	}
	cnt[p] ++ ;
}

void build(){
	int hh = 0, tt = -1;
	for(int i = 0; i < 26; i ++ ){
		if(tr[0][i]) q[ ++ tt] = tr[0][i];
	}
	
	while(hh <= tt){
		int t = q[hh ++ ];
		
		for(int i = 0; i < 26; i ++ ){
			int p = tr[t][i];
			if(!p) tr[t][i] = tr[ne[t]][i];
			else{
				ne[p] = tr[ne[t]][i];
				q[ ++ tt] = p;
			}
		}
	}
}

int main()
{
	cin>>T;
	while(T -- ){
		cin>>n;
		memset(cnt, 0, sizeof cnt);
		memset(ne, 0, sizeof ne);
		memset(tr, 0, sizeof tr);
		ids = 0;
		int res = 0;
		
		for(int i = 0; i < n; i ++ ){
			cin>>str;
			insert();
		}
		
		build();
		
		cin>>str;
		for(int i = 0, j = 0; str[i]; i ++ ){
			int t = str[i] - 'a';
			
			j = tr[j][t];  //代表从j节点连到t节点的枝,j是从根节点开始
			int p = j;
			while(p){
				res += cnt[p];
				cnt[p] = 0;
				p = ne[p];
			}
		} 
		cout<<res<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值