您的位置:首页 > 其它

P3796 【模板】AC自动机(加强版)

2018-07-23 17:53 417 查看

P3796 【模板】AC自动机(加强版)

https://www.luogu.org/problemnew/show/P3796   分析:   AC自动机。   建出AC自动机,然后扫一遍文本串,顺着last,统计每个模式串出现的次数。     代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

const int N = 150100;

char str[1000100], s[155][75];

int ch
[26], fail
, val
, ans
, q
, last
, L, R, Index;

void clear() {
memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val));
memset(ans, 0, sizeof(ans));
memset(last, 0, sizeof(last));
memset(fail, 0, sizeof(fail));
Index = 0;
}
void Insert(char *s,int ID) {
int u = 0, len = strlen(s);
for (int i=0; i<len; ++i) {
int c = s[i] - 'a';
if (!ch[u][c]) ch[u][c] = ++Index;
u = ch[u][c];
}
val[u] = ID;
}
void build() {
L = 1, R = 0; fail[0] = 0;
for (int c=0; c<26; ++c) {
int u = ch[0][c];
if (u) fail[u] = 0, q[++R] = u, last[u] = 0;
}
while (L <= R) {
int u = q[L++];
for (int c=0; c<26; ++c) {
int v = ch[u][c];
if (!v) {
ch[u][c] = ch[fail[u]][c];
continue;
}
q[++R] = v;
int p = fail[u];
while (p && !ch

[c]) p = fail[p]; fail[v] = ch[p][c]; last[v] = val[fail[v]] ? fail[v] : last[fail[v]]; } } } void find(char *s) { int Ans = 0, u = 0, len = strlen(s); for (int i=0; i<len; ++i) { int c = s[i] - 'a'; u = ch[u][c]; if (val[u]) ans[val[u]] ++; int p = u; while (last[p]) { p = last[p]; if (val[p]) ans[val[p]] ++; } } } int main () { int n; while (~scanf("%d",&n) && n) { clear(); for (int i=1; i<=n; ++i) { scanf("%s",s[i]); Insert(s[i], i); } build(); scanf("%s",str); find(str); int mx = 0; for (int i=1; i<=n; ++i) mx = max(ans[i], mx); printf("%d\n",mx); for (int i=1; i<=n; ++i) { if (ans[i] == mx) printf("%s\n",s[i]); } } return 0; }

[p] 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: