AC自動機 洛谷 模板
阿新 • • 發佈:2020-07-15
#pragma warning(disable:4996) #include<iostream> #include<algorithm> #include<bitset> #include<tuple> #include<unordered_map> #include<fstream> #include<iomanip> #include<string> #include<cmath> #include<cstring> #include<vector> #include<map> #include<set> #include<list> #include<queue> #include<stack> #include<sstream> #include<cstdio> #include<ctime> #include<cstdlib> #define INF 0x3f3f3f3f #define inf 0x7FFFFFFF #define MOD 998244353 #define moD 1000000003 #define pii pair<int,string> #defineeps 1e-8 #define equals(a,b) (fabs(a-b)<eps) #define bug puts("bug") #define re register #define fi first #define se second const int maxn = 1e6 + 5; const double Inf = 10000.0; const double PI = acos(-1.0); typedef long long ll; typedef unsigned long long ull; using namespace std; char s[151][71];char ss[maxn]; int m; struct Aho { int Node_cnt, f[maxn], ch[maxn][26], cnt[maxn], val[maxn], last[maxn]; void clear() { memset(f, 0, sizeof f); memset(ch, 0, sizeof ch); memset(cnt, 0, sizeof cnt); memset(val, 0, sizeof val); memset(last, 0, sizeof last); Node_cnt = 0; } void insert(char* s, int idx) { int u = 0, n = strlen(s); for (int i = 0; i < n; i++) { int c = s[i] - 'a'; if (!ch[u][c]) ch[u][c] = ++Node_cnt; u = ch[u][c]; } val[u] = idx; } void getFail() { queue<int> q; q.push(0); while (!q.empty()) { int u = q.front(), k = f[u]; q.pop(); for (int c = 0; c < 26; c++) { int v = ch[u][c]; if (!v) { ch[u][c] = ch[k][c]; continue; } f[v] = u ? ch[k][c] : 0; last[v] = val[f[v]] ? f[v] : last[f[v]]; q.push(v); } } } void query(char *ss) { int u = 0, n = strlen(ss), res = 0; for (int i = 0; i < n; i++) { int c = ss[i] - 'a'; u = ch[u][c]; if (val[u]) cnt[val[u]]++; int v = last[u]; while (v) { if (val[v]) cnt[val[v]]++; v = last[v]; } } for (int i = 1; i <= m; i++) res = max(res, cnt[i]); printf("%d\n", res); for (int i = 1; i <= m; i++) if (cnt[i] == res) printf("%s\n", s[i]); return; } }AC; int main() { while (scanf("%d", &m), m) { AC.clear(); for (int i = 1; i <= m; i++) scanf("%s", s[i]), AC.insert(s[i], i); AC.getFail(); scanf("%s", ss); AC.query(ss); } }