AC自动机学习笔记
qqqaaazzz_qwq · · 个人记录
有什么用?
大多数时候用于解决“一个文本串,多个模式串”的字符串匹配问题。在此基础上,我们可以进行许多拓展。
怎么实现?
先将模式串建成字典树,然后对于字典树上的每个节点,我们都需要一个“fail”指针。
fail 指针的意义?
把从根到
贴张图:
求出
如果
最后,是统计答案。注意到经过
模板题 AC 代码:
#include <bits/stdc++.h>
#define FAST ios::sync_with_stdio(false);cin.tie(0)
using namespace std;
int n,m;
struct Node{
int c[26];
int fail;//失配指针
};
Node t[500010];
int g[500010];
vector<int> v[500010];
vector<int> G[500010];
int idx;
void Build_fail(){
queue<int> q;
for (int i=0;i<26;i++){
if(t[0].c[i]!=0){
q.push(t[0].c[i]);
t[t[0].c[i]].fail = 0;
}
}
while(!q.empty()){
int f = q.front();
q.pop();
for (int i=0;i<26;i++){
if(t[f].c[i]!=0){
q.push(t[f].c[i]);
t[t[f].c[i]].fail = t[t[f].fail].c[i];
}
else t[f].c[i] = t[t[f].fail].c[i];
}
}
return;
}
int l[500010],r[500010],cnt;
void dfs(int d){
++cnt;
l[d] = cnt;
for (auto i : G[d]) dfs(i);
r[d] = cnt;
return;
}
int tr[500010];
int lowbit(int x){
return (x&-x);
}
void add(int x,int c){
while(x<=cnt){
tr[x] += c;
x += lowbit(x);
}
return;
}
int query(int x){
int res = 0;
while(x){
res += tr[x];
x -= lowbit(x);
}
return res;
}
/*
4
she
her
eher
ers
shehers
*/
signed main()
{
cin >> n;
for (int i=1;i<=n;i++){
string s;
cin >> s;
int now = 0;
for (auto j : s){
if(t[now].c[j-'a']==0) t[now].c[j-'a'] = ++idx;
now = t[now].c[j-'a'];
}
g[i] = now;
}
Build_fail();
for (int i=1;i<=idx;i++){
G[t[i].fail].push_back(i);
}
dfs(0);
m = 1;//可以调整文本串的个数
for (int i=1;i<=m;i++){
string T;
cin >> T;
int now = 0;
vector<int> q;
for (auto j : T){
now = t[now].c[j-'a'];
q.push_back(l[now]);
add(l[now],1);
}
for (int j=1;j<=n;j++) cout << query(r[g[j]])-query(l[g[j]]-1) << "\n";
//cout << "\n";
for (auto j : q) add(j,-1);
}
return 0;
}
一些口胡的idea
匹配问题1
有
input:
4
appl
app
ple
ap
apple
output:
3 0 1 0 0
先把所有字符串都翻转一下,然后开头就变成了结尾。在 AC自动机 上面把每个节点会产生的子串个数记下来就好啦,并不难。
匹配问题2(AC自动机超级加强版)
input:
4
she
her
eher
ers
2
shehers
eherher
output:
1 0
1 2
1 1
1 0
令每个点的
具体实现就是上面的代码微调。
L 语言
link
阿狸的打字机
匹配问题2 的魔改版。
link