HDU 2222 Keywords Search(AC自动机)
2015-08-14 10:33
417 查看
Description
求文本串中出现了几次模式串
Input
第一行为用例组数T,每组用例第一行为一个整数n表示模式串个数,最后一行为文本串
Output
输出文本串中模式串出现次数
Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
Solution
AC自动机裸题
Code
求文本串中出现了几次模式串
Input
第一行为用例组数T,每组用例第一行为一个整数n表示模式串个数,最后一行为文本串
Output
输出文本串中模式串出现次数
Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
Solution
AC自动机裸题
Code
#include<cstdio> #include<algorithm> #include<iostream> #include<cstring> #include<queue> using namespace std; #define maxn 55 #define maxl 11111 struct Trie { int next[maxn*maxl][26],fail[maxn*maxl],end[maxn*maxl]; 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[]) { 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; 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[1111111]; 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; }
相关文章推荐
- HDU 1255 覆盖的面积 (线段树 + 离散化 + 扫描线)
- Nginx+Resin+JSP+Memcached+MySQL安装配置整合
- POJ 1751 Highways(最小生成树prim)
- String StringBuffer和StringBuilder的区别
- LightOJ 1258 Making Huge Palindromes (回文&KMP)
- 在flash builder里全局搜索里如何“全字匹配”搜索
- js正则控制文本框只能输入数字以及小数
- 管式超滤系统:管式超滤膜技术在饮水净化中作用解析
- HttpClient Get和Post
- 别以为真懂Openstack系列:虚拟机创建的50个步骤和100个知识点
- 别以为真懂Openstack系列:虚拟机创建的50个步骤和100个知识点
- java: system.gc()和 finalize 的使用情景
- win10看视频总是弹出realtek高清晰音频管理器怎么办?
- 多线程六 经典线程同步之信号量Semaphore
- Gnome桌面的定制(修改面板 修改右键菜单) [初级]
- 进制转换
- Linux环境Nginx安装多版本PHP
- 微软中国裁员曝光:在CD结束后!薪酬不变!
- 网络篇----NSURLSession下载篇
- jquery在线手册