当前位置:网站首页>AcWing 1282. Search Keyword Problem Solution ((AC Automata) Trie+KMP)+bfs)
AcWing 1282. Search Keyword Problem Solution ((AC Automata) Trie+KMP)+bfs)
2022-07-31 16:40:00 【QingQingDE23】
AcWing 1282. 搜索关键词((AC自动机)Trie+KMP)+bfs)
An algorithm that I wanted to learn a long time ago,But I didn't understand it before,Good thing I got it this time
希望ACAutomata can help meAC吧
#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节点连到tbranch of node,j是从根节点开始
int p = j;
while(p){
res += cnt[p];
cnt[p] = 0;
p = ne[p];
}
}
cout<<res<<endl;
}
return 0;
}
边栏推荐
- [pytorch] 1.7 pytorch and numpy, tensor and array conversion
- 基于C语言的编译器设计与实现
- AcWing 1282. 搜索关键词 题解((AC自动机)Trie+KMP)+bfs)
- 深度学习机器学习理论及应用实战-必备知识点整理分享
- 牛客 HJ18 识别有效的IP地址和掩码并进行分类统计
- The 2nd China PWA Developer Day
- Replication Latency Case (1) - Eventual Consistency
- The arm button controls the flashing of the led light (embedded button experiment report)
- Flutter 获取状态栏statusbar的高度
- jeecg master-slave database read-write separation configuration "recommended collection"
猜你喜欢
随机推荐
多主复制下处理写冲突(3)-收敛至一致的状态及自定义冲突解决逻辑
t-sne 数据可视化网络中的部分参数+
【源码解析】BeanFactory和FactoryBean
Qt实战案例(54)——利用QPixmap设计图片透明度
AcWing 1282. 搜索关键词 题解((AC自动机)Trie+KMP)+bfs)
server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none 失败
牛客 HJ3 明明的随机数
The new BMW 3 Series is on the market, with safety and comfort
百度网盘网页版加速播放(有可用的网站吗)
【pytorch】1.7 pytorch与numpy,tensor与array的转换
【TypeScript】深入学习TypeScript类型操作
MySQL常用语句整理
GP 6总体架构学习笔记
flutter设置statusbar状态栏的背景颜色和 APP(AppBar)内部颜色一致方法。
Qt practical cases (54) - using transparency QPixmap design pictures
MySQL多表联合查询
C程序是如何跑起来的01 —— 普通可执行文件的构成
Small program: Matlab solves differential equations "recommended collection"
Golang go-redis cluster模式下不断创建新连接,效率下降问题解决
Masterless Replication System (3)-Limitations of Quorum Consistency








![[TypeScript]OOP](/img/d7/b3175ab538906ac1b658a9f361ba44.png)
