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[p][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; }
相关文章推荐
- cjoj P1435 - 【模板题 USACO】AC自动机 && 洛谷 P3796 【模板】AC自动机(加强版)
- 洛谷 P3796 【模板】AC自动机(加强版)
- P3796 【模板】AC自动机(加强版)
- 洛谷 P3796 【模板】AC自动机(加强版)
- 洛谷P3796 【模板】AC自动机(加强版)
- 【洛谷P3796】【模板】AC自动机(加强版)
- P3796 【模板】AC自动机(加强版)
- luogu3796【模板】AC自动机(加强版)
- [洛谷3796]【模板】AC自动机(加强版)
- 【洛谷】3796 【模板】AC自动机(加强版)
- 洛谷P3796 - 【模板】AC自动机(加强版)
- luogu P3796【模板】AC自动机(加强版)
- 【模板】AC自动机(加强版) 洛谷3796 AC自动机
- luogu3796 【模板】AC自动机(加强版)
- hdu 2222 ac自动机 模板
- AC自动机 模板
- AC自动机 多模式串匹配 模板
- AC自动机模板
- 【HDU2896】病毒侵袭-AC自动机模板题
- HDOJ2222Keywords Search【AC自动机模板题】