Keywords Search
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 48950 Accepted Submission(s): 15626
Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.
Input
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters ‘a’-‘z’, and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.
Output
Print how many keywords are contained in the description.
Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
AC自动机裸题。。
附上本蒟蒻的代码:
#include<iostream>
#include<cstdio>
using namespace std;
#define MAXN 500001
char s[51],m[MAXN<<1];
int T,n,sz,ans,a[MAXN][27],q[MAXN],point[MAXN],danger[MAXN];
bool mark[MAXN];
int read()
{
int w=0,c=1; char ch=getchar();
while (ch<'0' || ch>'9')
{
if (ch=='-') c=-1;
ch=getchar();
}
while (ch>='0' && ch<='9')
w=w*10+ch-'0',ch=getchar();
return w*c;
}
void ins()
{
int now=1,len=strlen(s),i,t;
for (i=0;i<len;i++)
{
t=s[i]-'a'+1;
if (a[now][t]) now=a[now][t];
else now=a[now][t]=++sz;
}
danger[now]++;
}
void acmach()
{
int k,head=0,i,tail=1,now;
q[0]=1,point[1]=0;
while (head<tail)
{
now=q[head++];
for (i=1;i<=26;i++)
{
if (!a[now][i]) continue;
k=point[now];
while (!a[k][i]) k=point[k];
point[a[now][i]]=a[k][i];
q[tail++]=a[now][i];
}
}
}
void solve()
{
int k=1,len=strlen(m),i,t,j;
for (i=0;i<len;i++)
{
mark[k]=1;
t=m[i]-'a'+1;
while (!a[k][t]) k=point[k];
k=a[k][t];
if (!mark[k])
for (j=k;j;j=point[j])
{
ans+=danger[j];
danger[j]=0;
}
}
printf("%d\n",ans);
}
int main()
{
int i,j;
T=read();
while (T--)
{
sz=1,ans=0;
n=read();
for (i=1;i<=26;i++) a[0][i]=1;
while (n--)
{
scanf("%s",&s);
ins();
}
acmach();
scanf("%s",&m);
solve();
for (i=1;i<=sz;i++)
{
point[i]=danger[i]=mark[i]=0;
for (j=1;j<=26;j++)
a[i][j]=0;
}
}
return 0;
}