Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1048 Accepted Submission(s): 324
#include <iostream> #include <stdio.h> #include <string.h> #include <queue> #include <algorithm> #include <stdlib.h> using namespace std; typedef struct node { int id; node *fail; node *next[10]; node() { id = 0; fail = NULL; memset(next, 0, sizeof(next)); } }TreeNode; int res[10005]; int nCount = 0; bool flag = false; void Insert(TreeNode *pRoot, char Substr[], int id) { int nLen = strlen(Substr); TreeNode *p = pRoot; for (int i = 0; i < nLen; i++) { int index = Substr[i] - '0'; if (p->next[index] == NULL) { p->next[index] = new TreeNode; } p = p->next[index]; } p->id = id; } void BuildAC(TreeNode *pRoot) { queue<TreeNode*> Queue; Queue.push(pRoot); while(!Queue.empty()) { TreeNode *p = Queue.front(); Queue.pop(); for (int i = 0; i < 10; 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.push(p->next[i]); } } } } void Query(TreeNode *pRoot, char str[]) { TreeNode *p = pRoot; int nLen = strlen(str); for (int i = 0; i < nLen; i++) { int index = str[i] - '0'; 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->id != -1) { if (temp->id > 0) { res[nCount++] = temp->id; temp->id = -1; flag = true; } temp = temp->fail; } } } void DeleteNode(TreeNode *pRoot) { for (int i = 0; i < 10; i++) { if (pRoot != NULL) { DeleteNode(pRoot->next[i]); } } delete pRoot; } int main() { int m, n; scanf("%d%d", &m, &n); char temp[105]; char str[60001]; memset(str, 0, sizeof(str)); TreeNode *pRoot = new TreeNode; for (int i = 0; i < m; i++) { scanf("%s", temp); strcat(str, temp); } int num; for (int i = 0; i < n; i++) { while(1) { char ch = getchar(); if (ch == ']') { getchar(); break; } } scanf("%s", temp); Insert(pRoot, temp, i + 1); } BuildAC(pRoot); Query(pRoot, str); if (flag) { printf("Found key: "); for (int i = 0; i < nCount; i++) { printf(i == nCount - 1 ? "[Key No. %d]\n" : "[Key No. %d] ", res[i]); } } else { printf( "No key can be found !\n" ); } DeleteNode(pRoot); return 0; }