当前位置:网站首页>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;
}
边栏推荐
- 宁波大学NBU IT项目管理期末考试知识点整理
- 外媒所言非虚,苹果降价或许是真的在清库存
- tensorflow2.0 cnn(layerwise)
- 多主复制下处理写冲突(4)-多主复制拓扑
- 2020 WeChat applet decompilation tutorial (can applet decompile source code be used)
- .NET 20th Anniversary Interview - Zhang Shanyou: How .NET technology empowers and changes the world
- MySQL常用语句整理
- [TypeScript] In-depth study of TypeScript type operations
- 单细胞测序流程(单细胞rna测序)
- Character pointer assignment [easy to understand]
猜你喜欢
随机推荐
[pytorch] 1.7 pytorch and numpy, tensor and array conversion
server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none 失败
jeecg主从数据库读写分离配置「建议收藏」
form 表单提交后,使页面不跳转[通俗易懂]
研发过程中的文档管理与工具
组合学笔记(六)局部有限偏序集的关联代数,Möbius反演公式
Flutter gets the height of the status bar statusbar
[TypeScript]OOP
tensorflow2.0 cnn(layerwise)
Applicable Scenarios of Multi-Master Replication (1) - Multi-IDC
你辛辛苦苦写的文章可能不是你的原创
Stuck in sill idealTree buildDeps during npm installation, npm installation is slow, npm installation is stuck in one place
How Redis handles concurrent access
Design and Implementation of Compiler Based on C Language
牛客 HJ18 识别有效的IP地址和掩码并进行分类统计
Oracle动态注册非1521端口
js的toString方法
C语言-函数
tooltips使用教程(鼠标悬停时显示提示)
Delete table data or clear table









