洛谷 P3808 【模板】AC自动机(简单版) (AC自动机优化板子)
2024-09-06 23:43:21
题中有一个坑点,就是模式串可以相同,并且全部计数。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
const int N=maxn;
char str[maxn];
struct Dfa {
int trie[N][26],cnt;
int e[N];
int fail[N];
char ch;
void init(char c) {
memset(trie,0,sizeof(trie));
memset(e,0,sizeof(e));
memset(fail,0,sizeof(fail));
cnt=0;
ch=c;
}
void insert(char * s) {
int p=0;
for (int i=0;s[i];i++) {
int to=s[i]-ch;
if (trie[p][to]==0) {
trie[p][to]=++cnt;
}
p=trie[p][to];
}
e[p]++;
}
void build() {
queue<int> q;
for (int i=0;i<26;i++) {
if (trie[0][i]) {
q.push(trie[0][i]);
}
}
while (!q.empty()) {
int root=q.front();
q.pop();
for (int i=0;i<26;i++) {
if (trie[root][i]) {
fail[trie[root][i]]=trie[fail[root]][i];
q.push(trie[root][i]);
}
else {
trie[root][i]=trie[fail[root]][i];
}
}
}
}
long long query(char * s) {
long long ans=0;
int p=0;
for (int i=0;s[i];i++) {
p=trie[p][s[i]-ch];//第一层的空节点k trie[0][k]=0
for (int j=p;j&&~e[j];j=fail[j]) {
ans+=e[j];
e[j]=-1;
}
}
return ans;
}
}dfa;
int main()
{
int n;
dfa.init('a');
scanf("%d",&n);
while (n--) {
scanf("%s",str);
dfa.insert(str);
}
dfa.build();
scanf("%s",str);
printf("%lld\n",dfa.query(str));
return 0;
}
最新文章
- 网游中的网络编程系列1:UDP vs. TCP
- 【C51】单片机独立按键与矩阵按键
- 判断文件结束,feof……
- Can&#39;t connect to local MySQL server through socket
- 十、VueJs 填坑日记之在项目中使用Amaze UI
- 【Android 应用开发】 ActionBar 基础
- 微信公众号开发 包括服务器配置、java web项目搭建、tomcat手动发布web项目、微信开发所需的url和token验证 2017.12.2
- LeetCode算法题-Jewels and Stones(Java实现)
- elk 中kafka启动脚本和配置文件
- oracle 分组函数执行分析
- 联想笔记本Y7000P安装nvidia,cuda,tensorflow,pytorch
- es6安装babel包
- Ubuntu 安装 Zabbix 3.2详细步骤
- 【CodeForces】866D. Buy Low Sell High
- ubuntu15.10运行android studio出错unable to run mksdcard sdk tool
- Jenkins分享
- 好用的 convert freestyle jenkins jobs to pipeline 插件使用
- 新手C#ListView使用记录2018.08.03
- java 集合 HashSet 实现随机双色球 HashSet addAll() 实现去重后合并 HashSet对象去重 复写 HashCode()方法和equals方法 ArrayList去重
- 备份/还原MySQL数据库----MySQL Workbench
热门文章
- Books Exchange (hard version)
- Android Socket 通信
- Zigbee 与 WiFi 的区别
- 【转载】SpringMVC配置文件详解
- 第十七篇 Linux下常用命令汇总
- 6月28日至7月6日第一周小学期学习c++编程收获
- bitset 位运算
- 自己常用的Linux命令和Hadoop命令
- Spring错误:org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.Bi
- C#: switch语句的重构『网摘』