AC自动机 多模式串匹配 模板
2016-10-18 01:51
351 查看
AC自动机就是字典树+KMP,解决了一个串在字典树中的匹配问题。
const int maxn = 26; struct node{ node* fail; node* next[maxn]; int counts; node(){ fail = NULL; counts = 0; for(int i = 0; i < maxn; ++i) next[i] = NULL; } }; struct Trie{ node* root; queue<node*> q; Trie(){root = NULL;} void inserts(char str[]){ int len = strlen(str); if(!root) root = new node; node* now = root; for(int i = 0; i < len; ++i){ int idx = str[i]-'a';//transform if(now->next[idx] == NULL) now->next[idx] = new node; now = now->next[idx]; } ++(now->counts);//the counts of the words that suffix match } void build_fail(){ root->fail = NULL; q.push(root); while(!q.empty()){ node* now = q.front(); q.pop(); node* jump = NULL; for(int i = 0; i < maxn; ++i){ if(now->next[i] != NULL){ jump = now->fail; while(jump != NULL){ if(jump->next[i] != NULL){//equal now->next[i]->fail = jump->next[i]; break; } jump = jump->fail; } if(jump == NULL)//reach root now->next[i]->fail = root; q.push(now->next[i]); } } } } int query(char str[]){//return the count of the Tree-words in str int ans = 0, idx, len = strlen(str); node* p = root; for(int i = 0; i < len; ++i){ idx = str[i]-'a';////transform while(p->next[idx]==NULL && p!=root) p = p->fail; p = (p->next[idx]==NULL) ? root : p->next[idx]; node* jump = p; while(jump != root && jump->counts > 0){//find the words that suffix match ans += jump->counts; jump->counts = 0;//avoid repeat jump = jump->fail; } } return ans; } };
相关文章推荐
- AC自动机 - 多模式串匹配问题的基本运用 + 模板题 --- HDU 2222
- AC自动机 - 多模式串匹配问题的基本运用 + 模板题 --- HDU 2222
- UVa 11019 (AC自动机 二维模式串匹配) Matrix Matcher
- HDU 2896 AC自动机 模式串匹配
- 多模式串匹配之AC自动机算法(Aho-Corasick算法)简介与C语言程序实现源码参考
- 字符串匹配--AC自动机模板
- HDU 2896 病毒入侵 AC自动机 多模式串匹配
- AC自动机模板及对多模式匹配的理解
- HDU 3695 浅谈AC自动机模式串匹配算法+严格空间控制
- 多模式串匹配之AC自动机算法(Aho-Corasick算法)简介与C语言程序实现源码参考
- AC自动机 - 多模式串的匹配 --- HDU 3695 Computer Virus on Planet Pandora(模板题)
- hdu5384 AC自动机模板题,统计模式串在给定串中出现的个数
- KMP模式串匹配模板
- 模板模式小叙
- 模板模式在Spring 中的应用
- 深入浅出Java模式设计之模板方法模式
- TemplateMethod模板方法(行为型模式)
- 09月14日学习杂记(用两种模式操作数据库[模板模式与策略模式])
- Struts+Hibernate模板开发笔记---设计模式:门面
- JDBC | 模板模式&策略模式