hdu 2222 Keywords Search(ac自动机入门题)
2016-07-16 10:26
316 查看
/************************************************************ 题目: Keywords Search(hdu 2222) 链接: http://acm.hdu.edu.cn/showproblem.php?pid=2222 算法: ac自动机 算法思想: 多个字符串匹配,也就是相当于多个kmp *************************************************************/ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<queue> #include<vector> using namespace std; const int mx=1000000; char str[mx]; struct Node { int data; int fail; int count; int next[26]; void init(int a) { data=a; fail=0; count=0; fill(next,next+26,-1); } }; Node tree[mx]; int cut; void insert(char *s) { int p=0; for (int i=0;s[i];i++) { int k=s[i]-'a'; if (tree[p].next[k]==-1) { tree[cut].init(k); tree[p].next[k]=cut++; } p=tree[p].next[k]; } tree[p].count++; } void ac() { int k=0; queue<Node>q; q.push(tree[0]); while (!q.empty()) { Node u=q.front(); q.pop(); for (int i=0;i<26;i++) { if (u.next[i]!=-1) { if (u.data==-1) tree[u.next[i]].fail=0; else { int v=u.fail; while (v&&tree[v].next[i]==-1) v=tree[v].fail; tree[u.next[i]].fail=max(tree[v].next[i],0); } q.push(tree[u.next[i]]); } } } } int getans(char *s) { int k=0,ans=0; for (int i=0;s[i];i++) { int x=s[i]-'a'; while (k&&tree[k].next[x]==-1) k=tree[k].fail; k=tree[k].next[x]; if (k==-1) {k=0;continue;} int j=k; while (tree[j].count) { ans+=tree[j].count; tree[j].count=0; j=tree[j].fail; } ans+=tree[tree[j].fail].count; tree[tree[j].fail].count=0; } return ans; } int main() { int t; scanf("%d",&t); while (t--) { cut=0; tree[cut++].init(-1); int n; scanf("%d",&n); while (n--) { scanf("%s",str); insert(str); } ac(); scanf("%s",str); printf("%d\n",getans(str)); } }
相关文章推荐
- Steady Cow Assignment---poj3189(多重匹配+二分)
- 操作系统--虚拟存储器
- yii框架实现读写分离
- 从日志统计到大数据分析
- android 如何模拟漫游数据
- java多线程基本概念与简单实用
- Java中自定义异常的使用
- Memcached集群/分布式/高可用 及 Magent缓存代理搭建过程 详解
- liunx文件操作
- eclipse快捷键
- Python中的编码问题
- 快速排序
- 【PHP发展史】PHP5.2 到 PHP5.6 中新增的功能详解
- ios面试题
- 淘宝网前台应用性能优化实践
- html/css攻略历程
- JavaWEB小知识学习--原生AJAX
- 敏捷项目管理框架框架
- 系统架构师谈企业应用架构之系统设计规范与原则2
- 图文详解PHP环境搭建教程