1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 1e4 + 10, M = 1e6 + 10, S = 55; int n; int tr[N * S][26], cnt[N * S], idx; char str[M]; int q[N * S], ne[N * S]; void insert() { int p = 0; for(int i = 0; str[i]; i++) { int t = str[i] - 'a'; if(!tr[p][t]) tr[p][t] = ++idx; p = tr[p][t]; } cnt[p]++; } void build() { int hh = 0, tt = -1; for(int i = 0; i < 26; i++) { if(tr[0][i]) q[++tt] = tr[0][i]; } while(hh <= tt) { int t = q[hh++]; for(int i = 0; i < 26; i++) { int p = tr[t][i]; if(!p) tr[t][i] = tr[ne[t]][i]; else { ne[p] = tr[ne[t]][i]; q[++tt] = p; } } } } int main() { int T; cin >> T; while(T--) { memset(tr, 0, sizeof tr); memset(cnt, 0, sizeof cnt); memset(ne, 0, sizeof ne); idx = 0; cin >> n; for(int i = 0; i < n; i++) { cin >> str; insert(); } build(); cin >> str; int res = 0; for(int i = 0, j = 0; str[i]; i++) { int t = str[i] - 'a'; j = tr[j][t]; int p = j; while(p) { res += cnt[p]; cnt[p] = 0; p= ne[p]; } } cout << res <<'\n'; } return 0; }
|