HDU 2222 AC自动机模板题
2016-04-22 13:00
344 查看
题目: http://acm.hdu.edu.cn/showproblem.php?pid=2222
AC自动机模板题
我现在对AC自动机的理解还一般,就贴一下我参考学习的两篇博客的链接:
http://blog.csdn.net/niushuai666/article/details/7002823 http://www.cppblog.com/menjitianya/archive/2014/07/10/207604.html
AC自动机模板题
我现在对AC自动机的理解还一般,就贴一下我参考学习的两篇博客的链接:
http://blog.csdn.net/niushuai666/article/details/7002823 http://www.cppblog.com/menjitianya/archive/2014/07/10/207604.html
#include<stdio.h> #include<string.h> #include<queue> using namespace std; char key[55]; char des[1111111]; struct node{ node *fail; node *next[26]; int cnt; node(){ fail = NULL; cnt = 0; for(int i = 0;i<26;i++) next[i] = NULL; } }; node *root; void insert(char *str){ node *head = root; int len = strlen(str); for(int i = 0;i<len;i++){ int temp = str[i]-'a'; if(head->next[temp] == NULL) head->next[temp] = new node(); head = head->next[temp]; } head->cnt++; } void build(){ queue<node *>q; q.push(root); while(!q.empty()){ node *head = q.front(); q.pop(); for(int i = 0;i<26;i++){ if(head->next[i] != NULL){ if(head == root){ head->next[i]->fail = root; }else{ node *temp = head->fail; while(temp != NULL){ if(temp->next[i] != NULL){ head->next[i]->fail = temp->next[i]; break; } temp = temp->fail; } if(temp == NULL) head->next[i]->fail = root; } q.push(head->next[i]); } } } } int query(){ int len = strlen(des),ans = 0;; node *head = root; for(int i = 0;i<len;i++){ int index = des[i]-'a'; while(head->next[index] == NULL && head != root) head = head->fail; head = head->next[index]; if(head == NULL) head = root; node *temp = head; while(temp!=root && temp->cnt!=-1){ ans += temp->cnt; temp->cnt = -1; temp = temp->fail; } } return ans; } int main(){ int t; scanf("%d",&t); while(t--){ root = new node(); int n; scanf("%d",&n); for(int i = 0;i<n;i++){ scanf(" %s",key); insert(key); } build(); scanf(" %s",des); printf("%d\n",query()); } return 0; }
相关文章推荐
- sh.status()
- VS2010添加附加头文件和附加库方法
- instanceof
- 设计模式开篇(一)
- EventBus使用
- Android Logcat小结和adb常用命令
- [转]escape()、encodeURI()、encodeURIComponent()区别详解
- OpenCV读取图片并显示和保存图片
- 剑指offer面试题 二进制中1的个数
- 【数据结构】二叉树(前、中、后)序遍历的递归与非递归算法
- 一次GPRS调试引出的大发现--STM32发送字符串第一个字符丢失
- Android Studio常用快捷键
- H5在线编辑器优化总结
- OpenCV在Windows、Linux、Android、iOS上的安装
- log4j配置 logging.xml (转载)
- 如何给教授发邮件
- Sqoop 数据导入问题
- C++注释规范
- 发布网站配置IIS(把网上找到的解决方法综合了一下)
- Feuding Families and Former Friends: Unsupervised Learning for Dynamic Fictional Relationships-Naacl 2016-20160422