[AC自动机][HDU3065]
2015-10-03 16:34
218 查看
[code]//====================== // HDU 2222 // 求目标串中出现了几个模式串 //输入 //1 //5 //she //he //say //shr //her //yasherhs //==================== //这道题如果for一遍把不属于A-Z的变量改成Z+1 反而会超时 直接用next[1000*55][128]搞定算了 #include<stdio.h> #include<algorithm> #include<iostream> #include<string.h> #include<queue> char S[1001][51]; int num[1001]; using namespace std; struct Trie { int next[1000*55][128],fail[1000*55],end[1000*55]; int root,L; int newnode() { for(int i=0;i<128;i++) next[L][i]=-1; end[L++]=0; return L-1; } void init() { L=0; root=newnode(); } void insert(char buf[],int p) { int len = strlen(buf); int now = root; for(int i=0;i<len;i++) { if(next[now][buf[i]]==-1) next[now][buf[i]]=newnode(); now=next[now][buf[i]]; } end[now]=p; } void build() { queue<int>Q; fail[root]=root; for(int i=0;i<128;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<128;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]]; int temp=now; while(temp!=root) { num[end[temp]]++; temp=fail[temp]; } } return res; } void debug() { for(int i=0;i<L;i++) { printf("id = %3d,fail = %3d,end = %3d,chi = [",i,fail[i],end[i]); for(int j = 0;j <= 26;j++) printf("%2d",next[i][j]); printf("]\n"); } } }; int n; char s[300]; char buff[2000005]; Trie ac; void input() { memset(S,0,sizeof(S)); memset(num,0,sizeof(num)); ac.init(); for(int i=1;i<=n;i++) { scanf("%s",S[i]); ac.insert(S[i],i); } ac.build(); } int main() { // freopen("a.in","r",stdin); int T; while(cin>>n) { input(); scanf("%s",buff); ac.query(buff); for(int i=1;i<=n;i++) if(num[i]>0) { printf("%s: %d\n",S[i],num[i]); } } return 0; }
相关文章推荐
- POJ1469_COURSES(二部图最大匹配)
- 设置cookie倒计时让让表单自动提交
- 学习记录—yii2简单的登录功能实现
- Spring 别名的使用
- ORMLite框架(1)——入门用法
- 指针与数组
- android stdio中的project和module的概念
- 更新Podfile时半天没反应解决方案
- hdu4135Co-prime
- session在登录中的使用
- 数据结构——概论
- Win10 利用 easybcd 安装 Ubuntu 14.04
- linux下离线更新nessus漏洞插件的方法
- codeforces 455C C. Civilization(树形dp+树的直径+并查集)
- GDataXMLNode应用
- 搭建tomcat服务器,目标可通过外网ip访问本机
- 关于应急道占用问题
- unix高级编程
- AndroidStudio(2 begin --- material design )
- AppDelegate中几个常用的回调调用时机