LA 4670 (AC自动机 模板题) Dominating Patterns

时间:2023-03-09 15:01:02
LA 4670 (AC自动机 模板题) Dominating Patterns

AC自动机大名叫Aho-Corasick Automata,不知道的还以为是能自动AC的呢,虽然它确实能帮你AC一些题目。=_=||

AC自动机看了好几天了,作用就是多个模式串在文本串上的匹配。

因为有多个模式串构成了一颗Tire树,不能像以前一样线性递推失配函数f了,于是改成了BFS求失配函数。

白书上那个last数组(后缀链接)的含义就是:在Tire树的某个分支上虽然没有遇到单词节点,但是某个单词可能是已经匹配上的字串的后缀。

举个栗子:

有两个模式串:aaabbb, ab

现在已经匹配了aaab,现在的位置正在Tire树上aaabbb的分支上,明显没有遇到单词节点,但是注意到ab是aaab的后缀,也就是说我们虽然没有匹配到第一个模式串,但是找到第二个模式串ab了。

这就是last数组的作用。

 #include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <map>
using namespace std; const int SIGMA_SIZE = ;
const int MAXNODE = ;
const int MAXS = + ; map<string, int> ms; struct AhoCorasickAutomata
{
int ch[MAXNODE][SIGMA_SIZE];
int f[MAXNODE]; //失配函数
int val[MAXNODE];
int last[MAXNODE];
int cnt[MAXS];
int sz; void init()
{
memset(ch[], , sizeof(ch[]));
memset(cnt, , sizeof(cnt));
ms.clear();
sz = ;
} inline int idx(char c) { return c - 'a'; } //插入字符串s, v > 0
void insert(char* s, int v)
{
int u = , n = strlen(s);
for(int i = ; i < n; i++)
{
int c = idx(s[i]);
if(!ch[u][c])
{
memset(ch[sz], , sizeof(ch[sz]));
val[sz] = ;
ch[u][c] = sz++;
} u = ch[u][c];
}
val[u] = v;
ms[string(s)] = v;
} //统计每个字串出现的次数
void count(int j)
{
if(j)
{
cnt[val[j]]++;
count(last[j]);
}
} //在T中查找模板
void find(char* T)
{
int j = , n = strlen(T);
for(int i = ; i < n; i++)
{
int c = idx(T[i]);
while(j && !ch[j][c]) j = f[j];
j = ch[j][c];
if(val[j]) count(j);
else if(last[j]) count(last[j]);
}
} //计算失配函数
void getFail()
{
queue<int> q;
f[] = ;
for(int i = ; i < SIGMA_SIZE; i++)
{
int u = ch[][i];
if(u) { last[u] = ; f[u] = ; q.push(u); }
}
while(!q.empty())
{
int r = q.front(); q.pop();
for(int c = ; c < SIGMA_SIZE; c++)
{
int u = ch[r][c];
if(!u) continue;
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
}ac; const int maxn = + ;
char T[maxn], P[][]; int main()
{
//freopen("in.txt", "r", stdin); int n;
while(scanf("%d", &n) == && n)
{
ac.init();
for(int i = ; i <= n; i++) { scanf("%s", P[i]); ac.insert(P[i], i); }
scanf("%s", T);
ac.getFail();
ac.find(T);
int M = -;
for(int i = ; i <= n; i++) if(ac.cnt[i] > M) M = ac.cnt[i];
printf("%d\n", M);
for(int i = ; i <= n; i++)
if(ac.cnt[ms[string(P[i])]] == M)
printf("%s\n", P[i]);
} return ;
}

代码君