AC自动机 hdu2222
2016-01-06 15:34
357 查看
1 #include <iostream> 2 using namespace std; 3 4 struct Node{ 5 Node *next[26]; 6 Node* fail; 7 int count; 8 Node(){ 9 for (int i = 0; i < 26; i++){ 10 next[i] = NULL; 11 } 12 fail = NULL; 13 count = 0; 14 } 15 }; 16 char words[51], s[1000001]; 17 Node* d[500001]; 18 void insert(char words[], Node *root){ 19 int i, len = strlen(words), v; 20 Node *p = root; 21 for (i = 0; i < len; i++){ 22 v = words[i] - 'a'; 23 if (p->next[v] == NULL){ 24 p->next[v] = new Node(); 25 } 26 p = p->next[v]; 27 } 28 p->count++; 29 } 30 void build(Node *root){ 31 int head, tail, i; 32 Node *p, *temp; 33 head = 0; 34 tail = 0; 35 root->fail = NULL; 36 d[head] = root; 37 while (head <= tail){ 38 temp = d[head++]; 39 for (i = 0; i < 26; i++){ 40 if (temp->next[i] == NULL) continue; 41 if (temp == root){ 42 temp->next[i]->fail = root; 43 } 44 else{ 45 p = temp->fail; 46 while (p != NULL){ 47 if (p->next[i] != NULL){ 48 temp->next[i]->fail = p->next[i]; 49 break; 50 } 51 p = p->fail; 52 } 53 if (p == NULL){ 54 temp->next[i]->fail = root; 55 } 56 } 57 d[++tail] = temp->next[i]; 58 } 59 } 60 } 61 62 int query(char s[], Node* root){ 63 int ans = 0, len = strlen(s), i, v; 64 Node *p = root, *temp; 65 for (i = 0; i < len; i++){ 66 v = s[i] - 'a'; 67 while (p->next[v] == NULL && p != root){ 68 p = p->fail; 69 } 70 p = (p->next[v] != NULL) ? p->next[v] : root; 71 temp = p; 72 while (temp != root&&temp->count != -1){ 73 ans += temp->count; 74 temp->count = -1; 75 temp = temp->fail; 76 } 77 } 78 return ans; 79 } 80 81 int main(){ 82 int m, n, i; 83 Node *root; 84 cin >> m; 85 while (m--){ 86 root = new Node(); 87 cin >> n; 88 for (i = 0; i < n; i++){ 89 cin >> words; 90 insert(words, root); 91 } 92 build(root); 93 cin >> s; 94 cout << query(s, root) << endl; 95 } 96 }
View Code
相关文章推荐
- 字符串处理之后缀数组
- 线段树模板
- K短路 spfa + A*
- 最短路 spfa, dijkstra, Floyd
- FFT之大数乘法
- LA 2531 The K-league 最大流
- uva 11248 最小割
- 添加磁盘不需重启机器
- 巧用adb pull
- POJ2411 状态压缩dp
- 判断变量是否不为空,函数isset()、!empty()与!is_null()的比较
- POJ2823 单调队列
- 2015武大校赛
- 题集
- POJ 1459 最大流 第二题
- POJ 1293 网络流 第一题
- ACM的算法分类 2015-04-16 14:25 22人阅读 评论(0) 收藏
- 水 hdu5208 2015-04-20 21:03 36人阅读 评论(0) 收藏
- JAVA学习【2】错误:无法从静态上下文中引用非静态
- js条件语句false情况