1 5 she he say shr her yasherhs
3
AC自动机第一题,自己理解写的,所以比较挫,不过纪念下,这个代码改了三天- -||||
#include <stdio.h> #include <string.h> #include <queue> using namespace std; typedef struct { int word,fail,p,num; int next[26]; }Tree; Tree tree[15000005]; char str[1000005]; int up,ans; queue <int> q; void Add(char *str) { int i,j,n,now; n=strlen(str); now=0; for (i=0;i<n;i++) { if (tree[now].next[str[i]-'a']!=-1) now=tree[now].next[str[i]-'a']; else { tree[now].next[str[i]-'a']=up; tree[up].word=tree[up].fail=0; tree[up].num=str[i]-'a'; tree[up].p=now; memset(tree[up].next,-1,sizeof(tree[up].next)); now=up++; } } tree[now].word++; } void BFS() { int t,tag,i; q.push(0); while(!q.empty()) { tag=q.front(); q.pop(); for (i=0;i<26;i++) { if (tree[tag].next[i]!=-1) q.push(tree[tag].next[i]); } if (tree[tag].p==0) { tree[tag].fail=0; continue; } t=tree[tree[tag].p].fail; while(1) { if (tree[t].next[tree[tag].num]==-1) { if (t==0) { tree[tag].fail=0; break; } t=tree[t].p; } else { tree[tag].fail=tree[t].next[tree[tag].num]; break; } } } } void Count() { int i,j,now,n,tag; now=0; n=strlen(str); for (i=0;i<n;i++) { while(tree[now].next[str[i]-'a']==-1 && now!=0) { now=tree[now].fail; } if (tree[now].next[str[i]-'a']!=-1) now=tree[now].next[str[i]-'a']; tag=now; while(tag!=0 && tree[tag].word!=-1) { ans+=tree[tag].word; tree[tag].word=-1; tag=tree[tag].fail; } } } int main() { int T,i,j,n,now; scanf("%d",&T); while(T--) { scanf("%d",&n); tree[0].word=tree[0].fail=tree[0].p=0; memset(tree[0].next,-1,sizeof(tree[0].next)); up=1; for (i=0;i<n;i++) { scanf("%s",str); Add(str); } BFS(); scanf("%s",str); n=strlen(str); now=0; ans=0; Count(); printf("%d\n",ans); } return 0; }