标签:
#include<cstdio> #include<cstdlib> #include<queue> #include<cstring> using namespace std; const int sigma_size=26; char p[1005]; bool vis[255]; char s[5100005]; struct Trie { Trie* next[sigma_size]; Trie* fail; int v; Trie() { memset(next,0,sizeof(next)); fail=0; v=0; } }; struct AhoCorasickAutomata { Trie *root; inline int idx(char c){return c-‘A‘;} AhoCorasickAutomata() { root=new Trie(); } void Insert(char *s,int v) { int len=strlen(s); Trie* p=root; for(int i=0;i<len;i++) { int c=idx(s[i]); if(p->next[c]==0) { Trie* q=new Trie(); p->next[c]=q; } p=p->next[c]; } p->v=v; } void Getfail() { queue<Trie*>Q; root->fail=0; Q.push(root); while(!Q.empty()) { Trie* p=Q.front();Q.pop(); for(int i=0;i<sigma_size;i++) if(p->next[i]) { Trie* q=p->fail; while(q&&!q->next[i])q=q->fail; p->next[i]->fail=q?q->next[i]:root; Q.push(p->next[i]); } } } void Find(char* s) { Trie* p=root; for(int i=0,len=strlen(s);i<len;i++) { int c=idx(s[i]); while(p&&!p->next[c])p=p->fail; p=p?p->next[c]:root->next[c]; for(Trie* q=p;q&&!vis[q->v];q=q->fail)vis[q->v]=1; } } }; void read(char *s) { int len=0; s[len]=0; while(1) { char c=getchar(); if(c==‘\n‘){s[len]=0;break;} if(c==‘[‘) { int num=0; while(1) { char cc=getchar(); if(!(cc>=‘0‘&&cc<=‘9‘)) { while(num--)s[len++]=cc; getchar(); break; } num=num*10+cc-‘0‘; } } else s[len++]=c; } } void rev(char *s) { for(int i=0,len=strlen(s);i<len/2;i++) swap(s[i],s[len-i-1]); } void dfs(Trie *u) { for(int i=0;i<sigma_size;i++) if(u->next[i])dfs(u->next[i]); delete u; } int main() { int T; scanf("%d",&T); while(T--) { AhoCorasickAutomata ac; memset(vis,0,sizeof(vis)); int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%s",p),ac.Insert(p,i); ac.Getfail(); getchar(); read(s); ac.Find(s); rev(s); ac.Find(s); int ans=0; for(int i=1;i<=n;i++)if(vis[i])ans++; printf("%d\n",ans); dfs(ac.root); } return 0; }
HDU 3695 Computer Virus on Planet Pandora
标签:
原文地址:http://www.cnblogs.com/homura/p/5767027.html