HDOJ 2222
2014-04-30 18:36
337 查看
思路: AC自动机
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Node_Tree { int cnt; struct Node_Tree *child[26]; struct Node_Tree *fail; }Node; Node *root; char keywd[51]; char decpt[1000001]; Node *q[500001]; int tail = 0, head = 0; void insert() { if(keywd == NULL) return ; int i; char *p = keywd; Node *t = root; while(*p != '\0') { if(t->child[*p - 'a'] == NULL) { Node *temp = (Node *)malloc(sizeof(Node)); memset(temp, 0, sizeof(Node)); for(i = 0; i < 26; i ++) { temp->child[i] = NULL; } temp->cnt = 0; temp->fail = NULL; t->child[*p - 'a'] = temp; } t = t->child[*p - 'a']; p ++; } t->cnt ++; } void getfail() { int i; q[tail++] = root; while(tail != head) //BFS; { Node *p = q[head++]; Node *temp = NULL; for(i = 0; i < 26; i ++) { if(p->child[i] != NULL) { if(p == root) { p->child[i]->fail = root; } else { temp = p->fail; while(temp != NULL) { if(temp->child[i] != NULL) { p->child[i]->fail = temp->child[i]; break ; } temp = temp->fail; } if(temp == NULL) p->child[i]->fail = root; } q[tail++] = p->child[i]; } } } } int search() { int i, ret = 0; char *p = decpt; Node *t = root; while(*p != '\0') { while(t->child[*p - 'a'] == NULL && t != root) t = t->fail; t = t->child[*p - 'a']; if(t == NULL) t = root; Node *temp = t; while(temp != root && temp->cnt != -1) { ret += temp->cnt; temp->cnt = -1; temp = temp->fail; } p ++; } return ret; } int main(int argc, char const *argv[]) { int c, i, t; scanf("%d", &c); Node TREEROOT; root = &TREEROOT; while(c --) { for(i = 0; i < 30; i ++) { root->child[i] = NULL; root->cnt = 0; root->fail = NULL; } tail = head = 0; memset(decpt, 0, sizeof(decpt)); memset(keywd, 0, sizeof(keywd)); scanf("%d", &t); while(t --) { scanf("%s", keywd); insert(); memset(keywd, 0, sizeof(keywd)); } getfail(); scanf("%s", decpt); printf("%d\n", search()); } return 0; }
相关文章推荐
- hdoj-2222 Keywords Search(AC自动机)
- HDOJ2222 AC自动机模版题
- 两天AC自动机的学习 HDOJ2222 HDOJ 2896
- (AC自动机)HDOJ2222
- HDOJ 2222 Keywords Search
- HDOJ-2222 (AC自动机模板)
- 【AC自动机】 HDOJ 2222 Keywords Search
- HDOJ 2222: Keywords Search
- { AC自动机 }hdoj2222
- [HDOJ2222]Keywords Search
- HDOJ 2222 - Keywords Search 更新AC自动机模板...用类来表示
- ACM HDOJ 2222 (Keywords Search)
- [HDOJ2222]Keywords Search(AC自动机)
- HDOJ 2222 AC自动机模板题
- HDOJ 2222
- hdoj 2222 Keywords Search 【AC自己主动机 入门题】 【求目标串中出现了几个模式串】
- HDOJ 2222 Keywords Search
- hdoj 2222-Keywords Search解题报告
- HDOJ 题目2222 Keywords Search(AC自动机)
- hdoj--2222 Keywords Search(AC自动机)