当前位置:网站首页>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;
}
边栏推荐
- MySQL常用语句整理
- 复制延迟案例(3)-单调读
- Flutter gets the height of the status bar statusbar
- 二分查找的细节坑
- LevelSequence源码分析
- Stuck in sill idealTree buildDeps during npm installation, npm installation is slow, npm installation is stuck in one place
- 华为顶级工程师历时9年总结的“趣谈网络协议”PDF文档,太强了
- [Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development
- 复杂高维医学数据挖掘与疾病风险分类研究
- Huawei's top engineers lasted nine years "anecdotal stories network protocol" PDF document summary, is too strong
猜你喜欢

adb shell 报错error: device unauthorized

外媒所言非虚,苹果降价或许是真的在清库存

动态规划(一)

adb shell error error: device unauthorized

【C语言】LeetCode27.移除元素

【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发

The 2nd China PWA Developer Day

EF Core 2.2中将ORM框架生成的SQL语句输出到控制台

How C programs run 01 - the composition of ordinary executable files

Graham's Scan method for solving convex hull problems
随机推荐
After the form is submitted, the page does not jump [easy to understand]
Qt实战案例(54)——利用QPixmap设计图片透明度
Applicable Scenarios of Multi-Master Replication (1) - Multi-IDC
【pytorch】pytorch 自动求导、 Tensor 与 Autograd
MySQL常用语句整理
How to switch remote server in gerrit
【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作
C程序是如何跑起来的01 —— 普通可执行文件的构成
[7.28] Code Source - [Fence Painting] [Appropriate Pairs (Data Enhanced Version)]
Visualize GraphQL schemas with GraphiQL
你辛辛苦苦写的文章可能不是你的原创
【网络通信三】研华网关Modbus服务设置
Character pointer assignment [easy to understand]
t-sne 数据可视化网络中的部分参数+
牛客网刷题(四)
基于ABP实现DDD
tensorflow2.0 cnn(layerwise)
[pytorch] 1.7 pytorch and numpy, tensor and array conversion
Implementing DDD based on ABP
复杂高维医学数据挖掘与疾病风险分类研究