【luogu P3808 AC自动机(简单版)】 模板
2024-08-27 22:06:37
题目链接:https://www.luogu.org/problemnew/show/P3808
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000010;
int n, trie[maxn][27], next[maxn], tot, vis[maxn];
char s[maxn];
queue<int> q;
void _insert(char s[])
{
int now = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
int x = s[i]-'a';
if(!trie[now][x])
trie[now][x] = ++tot;
now = trie[now][x];
}
vis[now]++;
}
void get_next()
{
for(int i = 0; i < 26; i++)
{
if(trie[0][i])
{
next[trie[0][i]] = 0;
q.push(trie[0][i]);
}
}
while(!q.empty())
{
int cnt = q.front(); q.pop();
for(int i = 0; i < 26; i++)
{
if(trie[cnt][i])
{
next[trie[cnt][i]] = trie[next[cnt]][i];
q.push(trie[cnt][i]);
}
else
trie[cnt][i] = trie[next[cnt]][i];
}
}
}
int find(char s[])
{
int now = 0, ans = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
int x = s[i]-'a';
now = trie[now][x];
for(int k = now; k&&~vis[k]; k = next[k])
{
ans += vis[k];
vis[k] = -1;
}
}
return ans;
}
int main()
{
std::ios::sync_with_stdio(false);
cin>>n;
for(int i = 1; i <= n; i++)
{
cin>>s;
_insert(s);
}
get_next();
cin>>s;
cout<<find(s);
return 0;
}
最新文章
- 北京培训记day2
- codevs2645 Spore
- Alpha版本十天冲刺——Day 7
- css选择器选择顺序是从右往左的,为什么?
- Difference Between Vector and Deque in C++
- UVA247- Calling Circles(有向图的强连通分量)
- ng-cli
- A tutorial on Principal Components Analysis | 主成分分析(PCA)教程
- WP8.1应用双击返回键退出程序。
- STM32F10XX存储器细节
- undefined 与null的区别与差异
- SOA和微服务架构
- MinGW安装与使用简介
- C++程序调用python3
- Ubuntu 12.04上安装 MongoDB并运行
- oracle 启动em (使用浏览器打开)
- 概念:dependency injection, IOC, vs callback
- Windows XP Ghost系统安装
- 10W年薪和30W+年薪的产品经理差距在哪?
- c#按照指定长度切分字符串