HDU 2222 Keywords Search
来源:互联网 发布:怎么添加淘宝收货地址 编辑:程序博客网 时间:2024/06/12 20:43
ac自动机模板题。
#include<iostream>#include<string>#include<cstring>#include<cstdio>#include<cmath>#include<iomanip>#include<map>#include<algorithm>#include<queue>#include<set>#define inf 10000000#define pi acos(-1.0)#define eps 1e-8#define seed 131using namespace std;typedef pair<int,int> pii;typedef unsigned long long ULL;typedef long long LL;const int maxn=100005;char buf[1000005];int n;const int maxnode=500010;const int sigma_size=26;struct Trie{ int root; int ch[maxnode][sigma_size]; int val[maxnode]; int fail[maxnode]; int sz; Trie(){ sz=1;root=0; memset(ch[0],0,sizeof(ch[0])); } void init() { sz=1;root=0; memset(ch[0],0,sizeof(ch[0])); } int idx(char c){ return c-'a'; } void insert(char* s) { int u=0,len=strlen(s); for(int i=0;i<len;i++) { int c=idx(s[i]); if(!ch[u][c]){ memset(ch[sz],0,sizeof(ch[sz])); val[sz]=0; ch[u][c]=sz++; } u=ch[u][c]; } val[u]++; } void build() { queue<int>que; fail[root]=root; for(int i=0;i<sigma_size;i++){ if(ch[root][i]==0) ch[root][i]=root; else { fail[ch[root][i]]=root; que.push(ch[root][i]); } } while(!que.empty()) { int now=que.front(); que.pop(); for(int i=0;i<sigma_size;i++) { if(ch[now][i]==0) ch[now][i]=ch[fail[now]][i]; else { fail[ch[now][i]]=ch[fail[now]][i]; que.push(ch[now][i]); } } } } int query(char buf[]) { int len=strlen(buf); int now=root; int ans=0; for(int i=0;i<len;i++) { now=ch[now][buf[i]-'a']; int temp=now; while(temp!=root) { ans+=val[temp]; val[temp]=0; temp=fail[temp]; } } return ans; }};Trie ac;int main(){ int t; scanf("%d",&t); while(t--) { ac.init(); scanf("%d",&n); 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;}
0 0
- hdu 2222 Keywords Search
- hdu 2222 Keywords Search
- HDU-2222 Keywords Search
- hdu 2222 Keywords Search
- Hdu 2222 Keywords Search
- hdu 2222-Keywords Search
- hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- Hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU - 2222 Keywords Search
- 提升Java的锁性能
- 【算法题】如何判断一个二叉树是平衡二叉树
- Retina与计算机图形的基本原理
- Android中Button的几种点击事件写法
- 三位数使用三进制进行全排列
- HDU 2222 Keywords Search
- pgpool + postgres 读写分离配置(4)
- 排列组合:poj 3252 Round Numbers
- 网络编程——基于消息的异步套接字编程
- Ural 1277 cops ans thieves (最小割模型)
- 用PULL解析器解析XML文件
- pgpool + postgres 读写分离配置(5)
- Android异常汇集----1. android.view.InflateExce: Binary XML file line #6: Error inflating class com.examp
- HDU 2896 病毒侵袭