AC自动机模板
2013-03-08 16:31
281 查看
首先是参考胡浩大神的数组模拟指针的模板,超简洁。
View Code
View Code
#define M 57 #define N 1000007 using namespace std; struct node { node *fail; node *next[26]; int cnt; void newnode()//生成节点 { fail = NULL; for (int i = 0; i < 26; ++i) { next[i] = NULL; } cnt = 0; } }; class Ac_Automat { node *q ,H ,*root; int fr,tl,t; public: // 初始化 void init() { fr = tl = 0; t = 0; H[t].newnode(); root = &H[t++]; } // 插入单词 void insert(char *s) { int i,k,len; len = strlen(s); node *p = root; for (i = 0; i < len; ++i) { k = s[i] - 'a'; if (p->next[k] == NULL) { H[t].newnode(); p->next[k] = &H[t++]; } p = p->next[k]; } p->cnt++; } // 建立失败指针 void build() { root->fail = NULL; q[tl] = root; while (fr <= tl) { node *tmp = q[fr++]; node *p = NULL; for (int i = 0; i < 26; ++i) { if (tmp->next[i]) { if (tmp == root) tmp->next[i]->fail = root; else { p = tmp->fail; while (p != NULL) { if (p->next[i]) { tmp->next[i]->fail = p->next[i]; break; } p = p->fail; } if (p == NULL) tmp->next[i]->fail = root; } q[++tl] = tmp->next[i]; } } } } // 查找 int query(char *s) { int res = 0; node *p = root; int len = strlen(s); for (int i = 0; i < len; ++i) { int k = s[i] - 'a'; while (p->next[k] == NULL && p != root) p = p->fail; p = p->next[k]; if (p == NULL) p = root; node *tmp = p; while (tmp != root && tmp->cnt != -1) { res += tmp->cnt; tmp->cnt = - 1; tmp = tmp->fail; } } return res; } }ac;
相关文章推荐
- HDU 2222 (AC自动机模板题)
- hdu2222Keywords Search(AC自动机模板题)
- Ac自动机模板代码
- HDU 2222 Keywords Search(AC自动机模板题)
- 关键词匹配(Ac自动机模板题)
- HDU 2896 病毒侵袭 (AC自动机数组型模板)
- hihoCoder-1036 (AC自动机模板题)
- 【HDU】病毒侵袭(AC自动机模板题)
- HDU 2896 (AC自动机模板题)
- AC自动机模板 LA4670 Dominating Patterns 出现次数最多的字串 BNUOJ11552 UVA1449
- AC自动机模板2(【CJOJ1435】)
- hdu 2222 AC自动机静态模板
- HDU 2222 Keywords Search(AC自动机模板题)
- hdu 5384 Danganronpa(AC自动机模板题)
- Duan2baka的AC自动机模板!
- AC自动机模板 LA4670
- 文章标题 UVALive 4670 : Dominating Patterns (AC自动机模板题)
- HDU 2896 病毒侵袭(AC自动机/模板题)
- [ACM模板]AC自动机
- AC自动机模板->kuangbin