hdu 2222(AC自动机 裸题)
2016-04-12 17:02
288 查看
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<algorithm> #include<cstdlib> #include<map> #include<queue> #include <deque> #include <list> #include <ctime> #include <stack> #include <vector> #include<iomanip> #include<set> #define Maxn 500010 #define mod typedef long long ll; #define FOR(i,j,n) for(int i=j;i<=n;i++) #define DFR(i,j,k) for(int i=j;i>=k;--i) #define lowbit(a) a&-a #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define mem(a) memset(a,0,sizeof(a)) #define eps 1e-9 const int inf = 0x3f3f3f3f; const double pi = acos(-1.0); using namespace std; char str[1000010],keyword[51]; int head,tail; struct node { node * fail; node * next[26]; int counter; node() { fail=NULL; counter=0; FOR(i,0,25)next[i]=NULL; } }*q[Maxn]; node *root; void Insert(char *str) { int temp,len; node *p=root; len=strlen(str); FOR(i,0,len-1) { temp=str[i]-'a'; if(p->next[temp]==NULL)p->next[temp]=new node(); p=p->next[temp]; } p->counter++; } void buildAC() { q[tail++]=root; while(head!=tail) { node *p=q[head++]; node *temp=NULL; FOR(i,0,25) { if(p->next[i]!=NULL) { if(p==root)p->next[i]->fail=root; else { temp=p->fail; while(temp!=NULL){ if(temp->next[i]!=NULL) {p->next[i]->fail=temp->next[i];break;} temp=temp->fail;} if(temp==NULL) p->next[i]->fail=root; } q[tail++]=p->next[i]; } } } } int query() { int index,len,result; node *p=root; result=0; len=strlen(str); FOR(i,0,len-1) { index=str[i]-'a'; while(p->next[index]==NULL&&p!=root) p=p->fail; p=p->next[index]; if(p==NULL)p=root; node *temp=p; while(temp!=root && temp->counter!=-1) { result += temp->counter; temp->counter=-1; temp=temp->fail; } } return result; } int main() { int T,num;cin>>T; FOR(i,1,T) {head=tail=0; root =new node(); scanf("%d",&num); getchar(); FOR(j,1,num) {gets(keyword); Insert(keyword); } // buildAC(); buildAC(); scanf("%s",str); printf("%d\n",query()); } return 0; }
相关文章推荐
- HDU4758 AC自动机+DP (HDU4758与HDU2222)
- AC自动机-一般算法实现
- 字符串的多模式匹配
- BZOJ1030 [JSOI2007]文本生成器【AC自动机+DP】
- BZOJ2434 [Noi2011]阿狸的打字机【AC自动机+dfs序+树状数组】
- AC自动机
- HDU_2222 大部分是别人的,有的地方稍有改动,代码有不完善的地方!
- AC自动机算法
- HDU-2222 Keyword Search
- AC自动机
- 【AC自动机】hdu2222 hdu2896 hdu3065 zoj3430 poj2778 hdu2243
- 【AC自动机】hdu2222 hdu2896 hdu3065 zoj3430 poj2778
- 两天AC自动机的学习 HDOJ2222 HDOJ 2896
- ac自动机+矩阵
- AC自动机——多模式串的匹配
- hdu2222 ac自动机。。。。
- AC自动机复习总结
- BZOJ 2462: [BeiJing2011]矩阵模板
- poj3691DNA repair
- hdu2222Keywords Search