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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| #include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; typedef long long ll; #define wfor(i,j,k) for(i=j;i<k;++i) #define mfor(i,j,k) for(i=j;i>=k;--i)
const int maxn = 500005; struct NODE { int cnt; int _next[26]; int _fail; }; NODE node[maxn]; void node_init(int cnt); void insert_char(char *s); void query(); void cal_fail(); char ss[1000005]; int num; int ans; int main() { std::ios::sync_with_stdio(false); #ifdef test freopen("F:\\Desktop\\question\\in.txt", "r", stdin); #endif int t; cin >> t; while (t--) { num = 0; ans = 0; node_init(0); int n; cin >> n; char tt[60]; int i; wfor(i, 0, n) { cin >> tt; insert_char(tt); } cal_fail(); cin >> ss; query(); cout << ans << endl; } return 0; } void node_init(int cnt) { memset(node[cnt]._next, -1, sizeof(node[cnt]._next)); node[cnt]._fail = -1; node[cnt].cnt = 0; } void insert_char(char *s) { int p = 0; int len = strlen(s); int i; wfor(i, 0, len) { int t = s[i] - 'a'; if (node[p]._next[t] == -1) { node_init(++num); node[p]._next[t] = num; } p = node[p]._next[t]; } node[p].cnt++; } void cal_fail() { queue<NODE>qu; int i; wfor(i, 0, 26) { if (node[0]._next[i] != -1) { int t = node[0]._next[i]; node[t]._fail = 0; qu.push(node[t]); } } while (!qu.empty()) { NODE temp = qu.front(); qu.pop(); wfor(i, 0, 26) { if (temp._next[i] != -1) { int p = temp._fail; while (p != -1 && node[p]._next[i] == -1) { p = node[p]._fail; } if (p == -1) { node[temp._next[i]]._fail = 0; } else if (node[p]._next[i] != -1) node[temp._next[i]]._fail = node[p]._next[i]; qu.push(node[temp._next[i]]); } } } } void query() { int len = strlen(ss); int i; int p = 0; wfor(i, 0, len) { int t = ss[i] - 'a'; while (p != 0 && node[p]._next[t] == -1) p = node[p]._fail; p = node[p]._next[t]; int temp; if (p != -1) temp = p; else { temp = p = 0; } while (temp != 0 && node[temp].cnt != -1) { ans += node[temp].cnt; node[temp].cnt = -1; temp = node[temp]._fail; } } }
|