标签:自动机 cout end using namespace include alt play ace
做了某题之后发现trie的AC自动机太垃圾了,动不动就TLE,然后我就去学了trie图。
#include<iostream> #include<cstdio> using namespace std; struct trie { int count; trie *fail,*nxt[26]; trie() { count=0; fail=NULL; for(int i=0;i<26;i++)nxt[i]=NULL; } }*q[1000000],*root=new trie(); int head,tail; char keyword[1000000],str[1000000]; void insert(char s[],trie *root) { int i=0,index; trie *p=root; while(s[i]) { index=s[i]-‘a‘; if(p->nxt[index]==NULL)p->nxt[index]=new trie(); p=p->nxt[index]; i++; } p->count++; } void build_ac(trie *root) { q[++tail]=root; while(head!=tail) { trie *p=q[++head]; for(int i=0;i<26;i++) if(p->nxt[i]!=NULL) { if(p==root)p->nxt[i]->fail=p; else p->nxt[i]->fail=p->fail->nxt[i]; q[++tail]=p->nxt[i]; } else { if(p==root)p->nxt[i]=p; else p->nxt[i]=p->fail->nxt[i]; } } } int ask(trie *root) { trie *p=root; int i=0,index,cnt=0; while(str[i]) { index=str[i]-‘a‘; p=p->nxt[index]; trie *temp=p; while(temp!=root && temp->count!=-1) cnt+=temp->count,temp->count=-1,temp=temp->fail; i++; } return cnt; } signed main() { int n,T; trie *p; cin>>T; while(T--) { p=new trie(); cin>>n; for(int i=1;i<=n;i++) { cin>>keyword; insert(keyword,p); } cin>>str; build_ac(p); cout<<ask(p)<<endl; } }
标签:自动机 cout end using namespace include alt play ace
原文地址:https://www.cnblogs.com/Al-Ca/p/11025281.html