1 5 she he say shr her yasherhs
3
ac自动机练手题。
#include<stdio.h> #include<string.h> #include<queue> #include<malloc.h> using namespace std; const int maxn = 1000005; int n, T; class tire { public: tire *down[26], *next; int end; tire(){ next = NULL; end = 0; memset(down, 0, sizeof(down)); } void insert(int &x, tire &y){ down[x] = &y; } }; class ac_automaton { private: tire *root; char S[maxn]; public: ac_automaton(){ root = new tire; } void insert() { scanf("%s", S); tire* j = root; for (int i = 0, k; S[i]; i++) { k = S[i] - 'a'; if (!j->down[k]) j->down[k] = new tire; j = j->down[k]; } j->end++; } void getnext() { tire *q, *j, *k; queue<tire*> p; p.push(root); while (!p.empty()) { q = p.front(); p.pop(); for (int i = 0; i < 26; i++) if (q->down[i]) { j = q->down[i]; k = q->next; while (k && !k->down[i]) k = k->next; if (k) j->next = k->down[i]; else j->next = root; p.push(j); } } } int work_out() { getnext(); int ans = 0; scanf("%s", S); tire*j = root, *u; for (int i = 0, k; S[i]; i++) { k = S[i] - 'a'; while (j && !j->down[k]) j = j->next; if (j) j = j->down[k]; else j = root; for (u = j; u != root && u->end >= 0; u = u->next) { ans += u->end; u->end = -1; } } return ans; } }; int main() { scanf("%d", &T); while (T--) { ac_automaton f; scanf("%d", &n); while (n--) f.insert(); printf("%d\n",f.work_out()); } return 0; }
#include<stdio.h> #include<string.h> #include<queue> #include<malloc.h> using namespace std; const int maxn = 1000005; class tire { public: tire *down[26], *next; int end; tire(){ next = NULL; end = 0; memset(down, 0, sizeof(down)); } void assign(){ next = NULL; end = 0; memset(down, 0, sizeof(down)); } }; class ac_automaton { private: tire *root; char s[maxn]; char S[maxn]; public: ac_automaton(){ root = new tire; } void clear(){ root = new tire; } void insert() { scanf("%s", s); tire* j = root; for (int i = 0, k; s[i]; i++) { k = s[i] - 'a'; if (!j->down[k]) j->down[k] = new tire; j = j->down[k]; } j->end++; } void getnext() { queue<tire*> p; tire *q, *k, *j; root->next = root; for (int i = 0; i < 26; i++) if (root->down[i]) { q = root->down[i]; q->next = root; p.push(q); } else root->down[i] = root; while (!p.empty()) { q = p.front(); p.pop(); k = q->next; for (int i = 0; i < 26; i++) if (q->down[i]) { j = q->down[i]; j->next = k->down[i]; p.push(q->down[i]); } else q->down[i] = k->down[i]; } } void work_out() { int ans = 0; getnext(); scanf("%s", S); tire *j = root, *u; for (int i = 0, k; S[i]; i++) { k = S[i] - 'a'; j = j->down[k]; for (u = j; u != root&&u->end >= 0; u = u->next) { ans += u->end; u->end = -1; } } printf("%d\n", ans); } }; ac_automaton f; int T, n; int main() { scanf("%d", &T); while (T--) { f.clear(); scanf("%d", &n); while (n--) f.insert(); f.work_out(); } return 0; }