Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25356 Accepted Submission(s): 8280
node
#include <stdio.h> #include <iostream> #include <string.h> using namespace std; #define N 500010 char str[1000010]; typedef struct node { int nCount; node *fail; node *next[26]; node() { nCount = 0; fail = NULL; for (int i = 0; i < 26; i++) { next[i] = NULL; } } }TreeNode; TreeNode *Queue[N]; void Insert(TreeNode *pHead, char Keyword[]) { int nLen = strlen(Keyword); TreeNode *p = pHead; for (int i = 0; i < nLen; i++) { int index = Keyword[i] - 'a'; if (p->next[index] == NULL) { p->next[index] = new TreeNode; } p = p->next[index]; } p->nCount++; } void BuildAC(TreeNode *pRoot) { int head = 0, tail = 0; Queue[tail++] = pRoot; while(tail != head) { TreeNode *p = Queue[head++]; for (int i = 0; i < 26; i++) { if (p->next[i] != NULL) { if (p == pRoot) { p->next[i]->fail = pRoot; } else { TreeNode *temp = p->fail; while(temp != NULL) { if (temp->next[i] != NULL) { p->next[i]->fail = temp->next[i]; break; } temp = temp->fail; } if (temp == NULL) { p->next[i]->fail = pRoot; } } Queue[tail++] = p->next[i]; } } } } int Query(TreeNode *pRoot) { int result = 0; int nLen = strlen(str); TreeNode *p = pRoot; for (int i = 0; i < nLen; i++) { int index = str[i] - 'a'; while(p != pRoot && p->next[index] == NULL) { p = p->fail; } p = p->next[index]; if (p == NULL) { p = pRoot; } TreeNode *temp = p; while(temp != pRoot && temp->nCount != -1) { result += temp->nCount; temp->nCount = -1; temp = temp->fail; } } return result; } void DeleteNode(TreeNode *pHead) { for (int i = 0; i < 26; i++) { if (pHead != NULL) { DeleteNode(pHead->next[i]); } } delete pHead; } int main() { char Keyword[55]; int nCase; TreeNode *pHead = NULL; scanf("%d", &nCase); int n; while(nCase--) { scanf("%d", &n); pHead = new TreeNode; for (int i = 0; i < n; i++) { scanf("%s", Keyword); Insert(pHead, Keyword); } BuildAC(pHead); scanf("%s", str); printf("%d\n", Query(pHead)); DeleteNode(pHead); } return 0; }