LA4670 Dominating Patterns AC自动机模板

时间:2023-03-09 17:53:07
LA4670 Dominating Patterns  AC自动机模板

Dominating Patterns

每次看着别人的代码改成自己的模板都很头大。。。空间少了个0卡了好久

裸题,用比map + string更高效的vector代替蓝书中的处理方法

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define abs(a) ((a) < 0 ? (-1 * (a)) : (a))
inline void swap(int &a, int &b)
{
long long tmp = a;a = b;b = tmp;
}
inline void read(int &x)
{
x = ;char ch = getchar(), c = ch;
while(ch < '' || ch > '') c = ch, ch = getchar();
while(ch <= '' && ch >= '') x = x * + ch - '', ch = getchar();
if(c == '-') x = -x;
} const int INF = 0x3f3f3f3f;
const int MAXNODE = * * ; int ch[MAXNODE][], last[MAXNODE], root = , tag[MAXNODE], fail[MAXNODE], cnt, tot[MAXNODE];
std::vector<int> node[MAXNODE];
char s[][]; void insert(int x)
{
int now = root;
for(int i = ;s[x][i] != '\0';++ i)
{
int& tmp = ch[now][s[x][i] - 'a' + ];
if(tmp) now = tmp;
else now = tmp = ++ cnt;
}
++ tag[now];
node[now].push_back(x);
} int q[MAXNODE], he, ta, ma;
void build()
{
he = , ta = ; for(register int i = ;i <= ;++ i)
{
int u = ch[root][i];
if(u) q[ta ++] = u, fail[u] = last[u] = ;
} while(he < ta)
{
int now = q[he ++];
for(register int i = ;i <= ;++ i)
{
int u = ch[now][i];
if(!u)
{
ch[now][i] = ch[fail[now]][i];
continue;
}
q[ta ++] = u;
int v = fail[now];
while(v && !ch[v][i]) v = fail[v];
fail[u] = ch[v][i];
last[u] = tag[fail[u]] ? fail[u] : last[fail[u]];
}
}
} int n;
char T[]; void find()
{
int n = strlen(T + );
int j = root;
for(register int i = ;i <= n;++ i)
{
int c = T[i] - 'a' + ;
j = ch[j][c];
if(tag[j]) for(int k = ;k < node[j].size();++ k) ++ tot[node[j][k]], ma = max(ma, tot[node[j][k]]);
else if(last[j]) for(int k = ;k < node[last[j]].size();++ k) ++ tot[node[last[j]][k]], ma = max(ma, tot[node[last[j]][k]]);
}
} int main()
{
while(scanf("%d", &n) != EOF && n)
{
ma = , memset(tot, , sizeof(tot)), memset(ch, , sizeof(ch)), memset(tag, , sizeof(tag));
for(register int i = ;i <= cnt;++ i) node[i].clear();
cnt = ;
for(register int i = ;i <= n;++ i)
{
scanf("%s", s[i] + );
insert(i);
}
build();
scanf("%s", T + );
find();
printf("%d\n", ma);
for(register int i = ;i <= n;++ i)
if(tot[i] == ma) printf("%s\n", s[i] + );
}
return ;
}

LA4670