1 #include <iostream> 2 using namespace std; 3 4 struct Node{ 5 Node *next[26]; 6 Node* fail; 7 int count; 8 Node(){ 9 for (int i = 0; i < 26; i++){ 10 next[i] = NULL; 11 } 12 fail = NULL; 13 count = 0; 14 } 15 }; 16 char words[51], s[1000001]; 17 Node* d[500001]; 18 void insert(char words[], Node *root){ 19 int i, len = strlen(words), v; 20 Node *p = root; 21 for (i = 0; i < len; i++){ 22 v = words[i] - ‘a‘; 23 if (p->next[v] == NULL){ 24 p->next[v] = new Node(); 25 } 26 p = p->next[v]; 27 } 28 p->count++; 29 } 30 void build(Node *root){ 31 int head, tail, i; 32 Node *p, *temp; 33 head = 0; 34 tail = 0; 35 root->fail = NULL; 36 d[head] = root; 37 while (head <= tail){ 38 temp = d[head++]; 39 for (i = 0; i < 26; i++){ 40 if (temp->next[i] == NULL) continue; 41 if (temp == root){ 42 temp->next[i]->fail = root; 43 } 44 else{ 45 p = temp->fail; 46 while (p != NULL){ 47 if (p->next[i] != NULL){ 48 temp->next[i]->fail = p->next[i]; 49 break; 50 } 51 p = p->fail; 52 } 53 if (p == NULL){ 54 temp->next[i]->fail = root; 55 } 56 } 57 d[++tail] = temp->next[i]; 58 } 59 } 60 } 61 62 int query(char s[], Node* root){ 63 int ans = 0, len = strlen(s), i, v; 64 Node *p = root, *temp; 65 for (i = 0; i < len; i++){ 66 v = s[i] - ‘a‘; 67 while (p->next[v] == NULL && p != root){ 68 p = p->fail; 69 } 70 p = (p->next[v] != NULL) ? p->next[v] : root; 71 temp = p; 72 while (temp != root&&temp->count != -1){ 73 ans += temp->count; 74 temp->count = -1; 75 temp = temp->fail; 76 } 77 } 78 return ans; 79 } 80 81 int main(){ 82 int m, n, i; 83 Node *root; 84 cin >> m; 85 while (m--){ 86 root = new Node(); 87 cin >> n; 88 for (i = 0; i < n; i++){ 89 cin >> words; 90 insert(words, root); 91 } 92 build(root); 93 cin >> s; 94 cout << query(s, root) << endl; 95 } 96 }
原文:http://www.cnblogs.com/macinchang/p/4507088.html