标签:des style io os ar for div sp on
Description
Input
Output
Sample Input
1 5 she he say shr her yasherhs
Sample Output
3 题意:求单词出现的次数 思路:第一题AC自动机,套了模板#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int kind = 26; struct Node { Node *fail; Node *next[kind]; int count; Node() { fail = NULL; count = 0; for (int i = 0; i < kind; i++) next[i] = NULL; } } *q[500001]; char keyword[51]; char str[1000001]; int head, tail; void insert(char *str, Node *root) { Node *p = root; int i = 0, index; while (str[i]) { index = str[i] - 'a'; if (p->next[index] == NULL) p->next[index] = new Node(); p = p->next[index]; i++; } p->count++; } void buildAcAutomation(Node *root) { int i; root->fail = NULL; q[head++] = root; while (head != tail) { Node *temp = q[tail++]; Node *p = NULL; for (int i = 0; i < 26; i++) { if (temp->next[i] != NULL) { if (temp == root) temp->next[i]->fail = root; else { p = temp->fail; while (p != NULL) { if (p->next[i] != NULL) { temp->next[i]->fail = p->next[i]; break; } p = p->fail; } if (p == NULL) temp->next[i]->fail = root; } q[head++] = temp->next[i]; } } } } int query(Node *root) { int i = 0, cnt = 0, index, len = strlen(str); Node *p = root; while (str[i]) { index = str[i] - 'a'; while (p->next[index] == NULL && p != root) p = p->fail; p = p->next[index]; p = (p == NULL) ? root : p; Node *temp = p; while (temp != root && temp->count != -1) { cnt += temp->count; temp->count = -1; temp = temp->fail; } i++; } return cnt; } void del(Node *root) { for (int i = 0; i < kind; i++) if (root->next[i] != NULL) del(root->next[i]); free(root); } int main() { int n, t; scanf("%d", &t); while (t--) { head = tail = 0; Node *root = new Node(); scanf("%d", &n); getchar(); while (n--) { gets(keyword); insert(keyword, root); } buildAcAutomation(root); scanf("%s", str); printf("%d\n", query(root)); del(root); } return 0; }
HDU - 2222 Keywords Search (AC自动机)
标签:des style io os ar for div sp on
原文地址:http://blog.csdn.net/u011345136/article/details/39524171