标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 44331 Accepted Submission(s):
13933
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define T 500001 using namespace std; int t,n,m,cnt,ans,a[T][27],sum[T],p[T],q[T]; bool mark[T]; char s[1000009],ss[51]; inline int read() { int a=0,f=1; char c=getchar(); while (c<‘0‘||c>‘9‘) {if (c==‘-‘) f=-1; c=getchar();} while (c>=‘0‘&&c<=‘9‘) {a=a*10+c-‘0‘; c=getchar();} return a*f; } inline void insert() { scanf("%s",ss); int now=1,c,l=strlen(ss); for (int i=0;i<l;i++) { c=ss[i]-‘a‘+1; if (a[now][c]) now=a[now][c]; else now=a[now][c]=++cnt; } sum[now]++; } void build_fail() { int t=0,w=1,now; q[1]=1; p[1]=0; while (t<w) { now=q[++t]; for (int i=1;i<=26;i++) { if (!a[now][i]) continue; int k=p[now]; while (!a[k][i]) k=p[k]; p[a[now][i]]=a[k][i]; q[++w]=a[now][i]; } } } void acmach() { scanf("%s",s); int now=1,c,l=strlen(s); ans=0; for (int i=0;i<l;i++) { mark[now]=1; c=s[i]-‘a‘+1; while (!a[now][c]) now=p[now]; now=a[now][c]; if (!mark[now]) for (int x=now;x;x=p[x]) {ans+=sum[x]; sum[x]=0;} } } int main() { t=read(); while (t--) { n=read(); cnt=1; ans=0; for (int i=1;i<=26;i++) a[0][i]=1; for (int i=1;i<=n;i++) insert(); build_fail(); acmach(); printf("%d\n",ans); for (int i=1;i<=cnt;i++) { p[i]=sum[i]=mark[i]=0; for (int j=1;j<=26;j++) a[i][j]=0; } } return 0; }
[HDU2222]Keywords Search|AC自动机
标签:
原文地址:http://www.cnblogs.com/ws-fqk/p/4727724.html