HDU 2222 Keywords Search
2015-07-08 09:40
337 查看
经典自动模板机
#include <stdio.h> #include <algorithm> #include <iostream> #include <string.h> #include <queue> using namespace std; struct Trie { int next[500010][26],fail[500010],end[500010]; int root,L; int newnode() //开辟空间 { for(int i = 0;i < 26;i++) next[L][i] = -1; end[L++] = 0; return L-1; } void init() { L = 0; root = newnode(); } void insert(char buf[]) //trie树 { int len = strlen(buf); int now = root; for(int i = 0;i < len;i++) { if(next[now][buf[i]-'a'] == -1) next[now][buf[i]-'a'] = newnode(); now = next[now][buf[i]-'a']; } end[now]++; } void build() //失败指针 { queue<int>Q; fail[root] = root; for(int i = 0;i < 26;i++) if(next[root][i] == -1) next[root][i] = root; else { fail[next[root][i]] = root; //第一层指向root Q.push(next[root][i]); //继续 } while( !Q.empty() ) { int now = Q.front(); Q.pop(); for(int i = 0;i < 26;i++) if(next[now][i] == -1) //指向失败指针 next[now][i] = next[fail[now]][i]; else { fail[next[now][i]]=next[fail[now]][i]; //更新失败指针 Q.push(next[now][i]); } } } int query(char buf[]) { int len = strlen(buf); int now = root; int res = 0; for(int i = 0;i < len;i++) { now = next[now][buf[i]-'a']; int temp = now; while( temp != root ) { res += end[temp]; end[temp] = 0; temp = fail[temp]; } } return res; } }; char buf[1000010]; Trie ac; int main() { int T; int n; scanf("%d",&T); while( T-- ) { scanf("%d",&n); ac.init(); for(int i = 0;i < n;i++) { scanf("%s",buf); ac.insert(buf); } ac.build(); scanf("%s",buf); printf("%d\n",ac.query(buf)); } return 0; }
相关文章推荐
- js对象及对象继承
- jqGrid使用
- 解决ArcGIS10.3属性表中文乱码问题
- 大话软件测试与职业生涯
- Kafka 监控调研
- Java-抽象类和接口概述
- Linux rm删除文件夹命令
- [linux]安装opengl
- 如何修改android 5.x版本recovery mode 小机器人界面进入菜单,由volume up&power改为直接按power(如同android 4.x以前版本)
- 更具笔格:网络文案权威指南
- PV、UV、VV、IP的区别
- 【小测试】你真的知道blocks在Objective-C中是怎么工作的吗?
- java class文件生成jar包
- 泛型算法例子
- android菜鸟学习笔记15----Android Junit测试
- select、poll、epoll之间的区别总结[整理]
- Spring3+ibatis (SQL Server)+pager-taglib.tld查询分页的实现
- Git跨平台中文乱码临时解决方案
- logo设计中,你需要注意什么?
- Java-final