病毒侵袭持续中
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4389 Accepted Submission(s): 1571
Problem Description
小t非常感谢大家帮忙解决了他的上一个问题。然而病毒侵袭持续中。在小t的不懈努力下,他发现了网路中的“万恶之源”。这是一个庞大的病毒网站,他有着好多好多的病毒,但是这个网站包含的病毒很奇怪,这些病毒的特征码很短,而且只包含“英文大写字符”。当然小t好想好想为民除害,但是小t从来不打没有准备的战争。知己知彼,百战不殆,小t首先要做的是知道这个病毒网站特征:包含多少不同的病毒,每种病毒出现了多少次。大家能再帮帮他吗?
Input
第一行,一个整数N(1<=N<=1000),表示病毒特征码的个数。
接下来N行,每行表示一个病毒特征码,特征码字符串长度在1—50之间,并且只包含“英文大写字符”。任意两个病毒特征码,不会完全相同。
在这之后一行,表示“万恶之源”网站源码,源码字符串长度在2000000之内。字符串中字符都是ASCII码可见字符(不包括回车)。
接下来N行,每行表示一个病毒特征码,特征码字符串长度在1—50之间,并且只包含“英文大写字符”。任意两个病毒特征码,不会完全相同。
在这之后一行,表示“万恶之源”网站源码,源码字符串长度在2000000之内。字符串中字符都是ASCII码可见字符(不包括回车)。
Output
按以下格式每行一个,输出每个病毒出现次数。未出现的病毒不需要输出。
病毒特征码: 出现次数
冒号后有一个空格,按病毒特征码的输入顺序进行输出。
病毒特征码: 出现次数
冒号后有一个空格,按病毒特征码的输入顺序进行输出。
Sample Input
3
AA
BB
CC
ooxxCC%dAAAoen....END
Sample Output
AA: 2
CC: 1
解题方法:AC自动机。
#include <stdio.h> #include <iostream> #include <string.h> #include <queue> using namespace std; typedef struct node { int id; node *fail; node *next[26]; node() { id = 0; fail = NULL; memset(next, 0, sizeof(next)); } }TreeNode; int res[1005] = {0}; char Str[2000005]; void Insert(TreeNode *pRoot, char str[], int id) { int nLen = strlen(str); TreeNode *p = pRoot; for (int i = 0; i < nLen; i++) { int index = str[i] - 'A'; 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 < 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.push(p->next[i]); } } } } void Query(TreeNode *pRoot, char str[]) { TreeNode *p = pRoot; int nLen = strlen(str); for (int i = 0; i < nLen; i++) { if (!isupper(str[i])) { p = pRoot; continue; } 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) { if (temp->id > 0) { res[temp->id]++; } temp = temp->fail; } } } void DeleteNode(TreeNode *pRoot) { if (pRoot != NULL) { for (int i = 0; i < 26; i++) { DeleteNode(pRoot->next[i]); } } delete pRoot; } int main() { int n; while(scanf("%d", &n) != EOF) { char temp[1005][55]; memset(res, 0, sizeof(res)); TreeNode *pRoot = new TreeNode; for (int i = 1; i <= n; i++) { scanf("%s", temp[i]); Insert(pRoot, temp[i], i); } scanf("%s", Str); BuildAC(pRoot); Query(pRoot, Str); for(int i = 1; i <= n; i++) { if (res[i] != 0) { printf( "%s: %d ", temp[i], res[i]); } } DeleteNode(pRoot); } return 0; }