当前位置:网站首页>AcWing 1282. 搜索关键词 题解((AC自动机)Trie+KMP)+bfs)
AcWing 1282. 搜索关键词 题解((AC自动机)Trie+KMP)+bfs)
2022-07-31 16:32:00 【QingQingDE23】
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;
}
边栏推荐
猜你喜欢

仿生毛毛虫机器人源码

gerrit中如何切换远程服务器

Kubernetes principle analysis and practical application manual, too complete

智能垃圾桶(九)——震动传感器(树莓派pico实现)

使用互相关进行音频对齐

tooltips使用教程(鼠标悬停时显示提示)

2022年必读的12本机器学习书籍推荐

复杂高维医学数据挖掘与疾病风险分类研究

基于ABP实现DDD
![[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development](/img/f6/311d5a4c70993df6291250d2025d3f.jpg)
[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development
随机推荐
【7.29】Code Source - 【Arrangement】【Stone Game II】【Cow and Snacks】【Minimum Number of Spawns】【Sequence】
牛客网刷题(三)
MySQL multi-table union query
【pytorch】pytorch 自动求导、 Tensor 与 Autograd
Mariabackup implements incremental data backup for Mariadb 10.3
Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?
C language - function
Applicable scenario of multi-master replication (2) - client and collaborative editing that require offline operation
C language "the third is" upgrade (mode selection + AI chess)
Replication Latency Case (1) - Eventual Consistency
Dialogue with Zhuang Biaowei: The first lesson of open source
MySQL基础篇【单行函数】
js的toString方法
The 2nd China PWA Developer Day
LevelSequence源码分析
GP 6总体架构学习笔记
牛客 HJ18 识别有效的IP地址和掩码并进行分类统计
ML.NET related resources
i.MX6ULL driver development | 33 - NXP original network device driver reading (LAN8720 PHY)
Stuck in sill idealTree buildDeps during npm installation, npm installation is slow, npm installation is stuck in one place