HDU 2222 Keywords Search (AC自动机)
2010-12-29 22:04
441 查看
/* Author: ACb0y Date: 2011年12月29日21:59:25 Type: AC自动机 ProblemID: hdu 2222 */ #include <iostream> using namespace std; struct node { node * fail; node * next[26]; int count; }; node * queue[500005]; char keyword[55]; char str[1000005]; node * root; node * get_node() { node * p = (node *)malloc(sizeof(node)); p->count = 0; p->fail = NULL; memset(p->next, NULL, sizeof(p->next)); return p; } void insert(char * str) { int len = strlen(str); node * p_cur = root; for (int i = 0; i < len; ++i) { int pos = str[i] - 'a'; if (p_cur->next[pos] == NULL) { p_cur->next[pos] = get_node(); } p_cur = p_cur->next[pos]; } p_cur->count++; } void build_fail() { int front = 0; int rear = 0; root->fail = NULL; queue[rear++] = root; while (front < rear) { node * p_cur = queue[front++]; node * temp = NULL; for (int i = 0; i < 26; ++i) { if (p_cur->next[i] != NULL) { if (p_cur == root) { p_cur->next[i]->fail = root; } else { temp = p_cur->fail; while (temp != NULL) { if (temp->next[i] != NULL) { p_cur->next[i]->fail = temp->next[i]; break; } temp = temp->fail; } if (temp == NULL) { p_cur->next[i]->fail = root; } } queue[rear++] = p_cur->next[i]; } } } } int query() { int cnt = 0; int len = strlen(str); node * p_cur = root; for (int i = 0; i < len; ++i) { int pos = str[i] - 'a'; while (p_cur->next[pos] == NULL && p_cur != root) { p_cur = p_cur->fail; } p_cur = p_cur->next[pos]; if (p_cur == NULL) { p_cur = root; } node * temp = p_cur; while (temp != root && temp->count != -1) { cnt += temp->count; temp->count = -1; temp = temp->fail; } } return cnt; } void clear(node * root) { node * p_cur = root; for (int i = 0; i < 26; ++i) { if (p_cur->next[i] != NULL) { clear(p_cur->next[i]); } } free(p_cur); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif int cas; scanf("%d", &cas); while (cas--) { int n; root = get_node(); scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%s", keyword); insert(keyword); } build_fail(); scanf("%s", str); printf("%d/n", query()); } return 0; }
相关文章推荐
- 【HDU 2222】Keywords Search(AC自动机)
- hdu 2222 Keywords Search(AC自动机入门题)
- HDU 2222 Keywords Search(AC自动机模板题)
- hdu 2222: Keywords Search(AC自动机模板题)
- hdu 2222 Keywords Search(AC自动机)
- hdu 2222 Keywords Search(ac自动机入门题)
- hdu 2222 Keywords Search(AC自动机)
- HDU 2222 Keywords Search(AC自动机模板题)
- HDU 2222 Keywords Search(AC自动机)
- HDU---2222-Keywords Search(AC自动机)
- hdu 2222 Keywords Search (AC自动机)
- hdu 2222Keywords Search(AC自动机入门好题)
- HDU2222 Keywords Search —— AC自动机
- hdu 2222 Keywords Search (ac自动机)
- HDU 2222 Keywords Search(AC自动机)
- Hdu-2222 Keywords Search(AC自动机)
- hdu - 2222 - Keywords Search(AC自动机)
- HDU 2222 Keywords Search(AC自动机裸)
- HDU 2222 Keywords Search(AC自动机)
- hdu----(2222)Keywords Search(ac自动机)