P3796 【模板】AC自动机(加强版)
\(\color{#0066ff}{ 题目描述 }\)
有\(N\)个由小写字母组成的模式串以及一个文本串\(T\)。每个模式串可能会在文本串中出现多次。你需要找出哪些模式串在文本串\(T\)中出现的次数最多。
\(\color{#0066ff}{输入格式}\)
输入含多组数据。
每组数据的第一行为一个正整数\(N\),表示共有NN个模式串,\(1 \leq N \leq 150\)。
接下去\(N\)行,每行一个长度小于等于\(70\)的模式串。下一行是一个长度小于等于\(10^6\)的文本串\(T\)。
输入结束标志为\(N=0\)。
\(\color{#0066ff}{输出格式}\)
对于每组数据,第一行输出模式串最多出现的次数,接下去若干行每行输出一个出现次数最多的模式串,按输入顺序排列。
\(\color{#0066ff}{输入样例}\)
2
aba
bab
ababababac
6
beta
alpha
haha
delta
dede
tata
dedeltalphahahahototatalpha
0
\(\color{#0066ff}{输出样例}\)
4
aba
2
alpha
haha
\(\color{#0066ff}{数据范围与提示}\)
none
\(\color{#0066ff}{ 题解 }\)
这个因为要求次数,所以要一直跳fail统计全
而且节点的num也不用再改了
开个数组记录就行了qwq
#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL in() {
char ch; int x = 0, f = 1;
while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
return x * f;
}
struct AC {
protected:
struct node {
node *ch[26], *fail;
int num, id;
node() {
memset(ch, 0, sizeof ch);
fail = NULL;
num = id = 0;
}
void *operator new (size_t) {
static node *S = NULL, *T = NULL;
return (S == T) && (T = (S = new node[1024]) + 1024), S++;
}
};
node *root;
public:
AC() { root = new node(); }
void clr() { root = new node(); }
void ins(char *s, int id) {
node *o = root;
for(char *p = s; *p; p++) {
int pos = *p - 'a';
if(!o->ch[pos]) o->ch[pos] = new node();
o = o->ch[pos];
}
o->id = id, o->num++;
}
void build() {
std::queue<node*> q;
q.push(root);
while(!q.empty()) {
node *tp = q.front(); q.pop();
for(int i = 0; i <= 25; i++) {
if(tp == root) {
if(tp->ch[i]) tp->ch[i]->fail = root, q.push(tp->ch[i]);
else tp->ch[i] = root;
}
else {
if(tp->ch[i]) tp->ch[i]->fail = tp->fail->ch[i], q.push(tp->ch[i]);
else tp->ch[i] = tp->fail->ch[i];
}
}
}
}
void query(char *s, int *ans) {
node *o = root;
for(char *p = s; *p; p++) {
int pos = *p - 'a';
o = o->ch[pos];
for(node *v = o; v != root; v = v->fail) if(v->id) ans[v->id] += v->num;
}
}
}b;
char s[250][120];
char t[1005050];
int ans[250];
int main() {
while("call me qiangge") {
int n = in();
if(!n) break;
b.clr();
for(int i = 1; i <= n; i++) scanf("%s", s[i]), b.ins(s[i], i), ans[i] = 0;
scanf("%s", t);
b.build();
b.query(t, ans);
int max = 0;
for(int i = 1; i <= n; i++) max = std::max(max, ans[i]);
printf("%d\n", max);
for(int i = 1; i <= n; i++) {
if(ans[i] == max) {
for(char *p = s[i]; *p; p++) putchar(*p);
puts("");
}
}
}
return 0;
}
----olinr