Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <iostream>
- #include <cstring>
- #include <vector>
- #include <algorithm>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- typedef long long LL;
- #define P LL(1e9 + 7)
- #define N 55
- #define L int(2e5 + 5)
- struct node {
- int to[26], end;
- };
- int n, m, cnt_node;
- LL p[N], hash[N];
- bool sufpref[N];
- char t[N];
- node trie[L];
- void precalc() {
- p[0] = 1;
- for (int i = 1; i < N; i++)
- p[i] = p[i - 1] * P;
- }
- LL count_hash(int l, int r) {
- if (!l)
- return hash[r];
- return hash[r] - hash[l - 1] * p[r - l + 1];
- }
- int main() {
- srand(time(NULL));
- freopen("sufpref.in", "r", stdin);
- freopen("sufpref.out", "w", stdout);
- precalc();
- scanf("%d\n", &n);
- for (int i = 0; i < n; i++) {
- gets(t);
- int l = strlen(t);
- sufpref[0] = false;
- hash[0] = t[0];
- for (int j = 1; j < l; j++)
- hash[j] = hash[j - 1] * P + t[j], sufpref[j] = false;
- for (int j = 1; j <= l; j++) {
- if (count_hash(0, j - 1) == count_hash(l - j, l - 1)) {
- bool eq = true;
- for (int k = 0; k < 3; k++) {
- int pos = rand() % j;
- if (t[pos] != t[l - j + pos]) {
- eq = false;
- break;
- }
- }
- if (eq)
- sufpref[j - 1] = true;
- }
- }
- int now = 0;
- for (int j = 0; j < l; j++) {
- int sym = int(t[j] - 'a');
- if (!trie[now].to[sym]) {
- cnt_node++;
- trie[now].to[sym] = cnt_node;
- }
- now = trie[now].to[sym];
- if (sufpref[j])
- trie[now].end++;
- }
- }
- scanf("%d\n", &m);
- for (int i = 0; i < m; i++) {
- gets(t);
- int l = strlen(t);
- bool fail = false;
- int now = 0;
- for (int j = 0; j < l; j++) {
- int sym = int(t[j] - 'a');
- now = trie[now].to[sym];
- if (!now) {
- fail = true;
- break;
- }
- }
- if (!fail)
- printf("%d\n", trie[now].end);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement