1 #include<cstdio>
 2 #include<cstring>
 3 #include<queue>
 4 #define MAXN 1000000
 5 #define MAXM 26
 6 using namespace std;
 7 char str[MAXN];
 8 int size, ans;
 9 struct node {
10     int fail, cnt, next[MAXM];
11     bool vis;
12     void Init() {
13         fail = cnt = 0;
14         vis = false;
15         memset(next, 0, sizeof(next));
16     }
17 };
18 node tree[MAXN];
19 inline int GET(char ch) {
20     return ch - 'a';
21 }
22 void Insert(char *s) {
23     int now, t;
24     for (now = 0; *s; s++) {
25         t = GET(*s);
26         if (!tree[now].next[t]) {
27             tree[++size].Init();
28             tree[now].next[t] = size;
29         }
30         now = tree[now].next[t];
31     }
32     tree[now].cnt++;
33 }
34 void BFS() {
35     int now, i, temp;
36     queue<int> q;
37     q.push(0);
38     while (!q.empty()) {
39         now = q.front();
40         q.pop();
41         for (i = 0; i < MAXM; i++) {
42             if (tree[now].next[i]) {
43                 temp = tree[now].next[i];
44                 if (now)
45                     tree[temp].fail = tree[tree[now].fail].next[i];
46                 q.push(temp);
47             } else
48                 tree[now].next[i] = tree[tree[now].fail].next[i];
49         }
50     }
51 }
52 void Match(char *s) {
53     int now, t, temp;
54     for (now = 0; *s; s++) {
55         t = GET(*s);
56         now = tree[now].next[t];
57         for (temp = now; temp && !tree[temp].vis; temp = tree[temp].fail) {
58             ans += tree[temp].cnt;
59             tree[temp].vis = true;
60         }
61     }
62 }
63 int main() {
64     int c, n;
65     scanf("%d", &c);
66     while (c--) {
67         scanf("%d", &n);
68         tree[0].Init();
69         for (size = ans = 0; n--;) {
70             scanf(" %s", str);
71             Insert(str);
72         }
73         BFS();
74         scanf(" %s", str);
75         Match(str);
76         printf("%d\n", ans);
77     }
78     return 0;
79 }
posted on 2012-08-01 21:01  DrunBee  阅读(522)  评论(0编辑  收藏  举报