当前位置:网站首页>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;
}
边栏推荐
- t-sne 数据可视化网络中的部分参数+
- 上传图片-微信小程序(那些年的坑记录2022.4)
- adb shell 报错error: device unauthorized
- 【pytorch】pytorch 自动求导、 Tensor 与 Autograd
- 牛客网刷题(四)
- After Effects 教程,如何在 After Effects 中调整过度曝光的快照?
- 宁波大学NBU IT项目管理期末考试知识点整理
- Handling write conflicts under multi-master replication (4) - multi-master replication topology
- Intelligent bin (9) - vibration sensor (raspberries pie pico implementation)
- adb shell error error: device unauthorized
猜你喜欢
gerrit中如何切换远程服务器
上传图片-微信小程序(那些年的坑记录2022.4)
How C programs run 01 - the composition of ordinary executable files
使用互相关进行音频对齐
Kubernetes common commands
第二届中国PWA开发者日
6-22 Vulnerability exploit - postgresql database password cracking
[pytorch] pytorch automatic derivation, Tensor and Autograd
【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发
[TypeScript] In-depth study of TypeScript type operations
随机推荐
【7.29】代码源 - 【排列】【石子游戏 II】【Cow and Snacks】【最小生成数】【数列】
The 2nd China PWA Developer Day
2.索引及调优篇【mysql高级】
Character pointer assignment [easy to understand]
Flutter 获取状态栏statusbar的高度
6. 使用 Postman 工具高效管理和测试 SAP ABAP OData 服务
flutter设置statusbar状态栏的背景颜色和 APP(AppBar)内部颜色一致方法。
入职一个月反思
全新宝马3系上市,安全、舒适一个不落
js的toString方法
Visualize GraphQL schemas with GraphiQL
Small program: Matlab solves differential equations "recommended collection"
最新神作!阿里巴巴刚出炉的面试参考指南(泰山版),我直接狂刷29天
复制延迟案例(1)-最终一致性
update data table update
arm按键控制led灯闪烁(嵌入式按键实验报告)
Replication Latency Case (3) - Monotonic Read
[TypeScript] In-depth study of TypeScript type operations
Applicable Scenarios of Multi-Master Replication (1) - Multi-IDC
GP 6总体架构学习笔记