HDU 2222 Keywords Search
2015-02-04 15:39
253 查看
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 131 using 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; }
相关文章推荐
- HDU 2222 Keywords Search (AC自动机入门题目)
- HDU 2222 Keywords Search
- AC自动机初识&hdu 2222 Keywords Search
- HDU 2222- Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- hdu 2222 Keywords Search
- Keywords Search (HDU_2222) AC自动机
- hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU-2222 Keywords Search
- Keywords Search(hdu 2222)
- hdu 2222——Keywords Search
- HDU 2222 Keywords Search (AC自动机模版题)
- Ac自动机_hdu_2222_Keywords Search
- hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- Hdu 2222 Keywords Search