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
|
using namespace std; #define clr(a, x) memset(a, x, sizeof(a)) #define mp(x, y) make_pair(x, y) #define pb(x) push_back(x) #define X first #define Y second #define fastin ios_base::sync_with_stdio(0); cin.tie(0); typedef long long ll; typedef long double ld; typedef pair<int, int> PII; typedef vector<int> VI; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-6; struct { int next[500010][26], fail[500010], end[500010]; int root, L; int newnode() { for (int i = 0; i < 26; i++) next[L][i] = -1; end[L++] = 0; return L - 1; } void init() { L = 0; root = newnode(); } void insert(char buf[]) { int len = strlen(buf); int now = root; for (int i = 0; i < len; i++) { if (next[now][buf[i] - 'a'] == -1) next[now][buf[i] - 'a'] = newnode(); now = next[now][buf[i] - 'a']; } end[now]++; } void build() { queue<int> Q; fail[root] = root; for (int i = 0; i < 26; i++) if (next[root][i] == -1) next[root][i] = root; else { fail[next[root][i]] = root; Q.push(next[root][i]); } while (!Q.empty()) { int now = Q.front(); Q.pop(); for (int i = 0; i < 26; i++) if (next[now][i] == -1) next[now][i] = next[fail[now]][i]; else { fail[next[now][i]] = next[fail[now]][i]; Q.push(next[now][i]); } } } int query(char buf[]) { int len = strlen(buf); int now = root; int res = 0; for (int i = 0; i < len; i++) { now = next[now][buf[i] - 'a']; int temp = now; while (temp != root) { res += end[temp]; end[temp] = 0; temp = fail[temp]; } } return res; } void debug() { for (int i = 0; i < L; i++) { printf("id␣=␣%3d,fail␣=␣%3d,end␣=␣%3d,chi␣=␣[", i, fail[i], end[i]); for (int j = 0; j < 26; j++) printf("%2d", next[i][j]); printf("]n"); } } }; char buf[1000010]; Trie ac; int main() { int T; int n; scanf("%d", &T); while (T--) { scanf("%d", &n); ac.init(); for (int i = 0; i < n; i++) { scanf("%s", buf); ac.insert(buf); } ac.build(); scanf("%s", buf); printf("%dn", ac.query(buf)); } system("pause"); return 0; }
|
近期评论