【hdu2222】Keywords Search

来源:互联网 发布:linux u盘文件系统 编辑:程序博客网 时间:2024/05/16 13:39

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自动机模板by hzwer

代码(fail指针版)

#include<cstdio>#include<cstring>#include<iostream>using namespace std;inline int read(){    int x=0,f=1;char ch=getchar();    while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}    while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}    return x*f;}char s[51],m[1000001];int T,n,tot,ans;int a[500001][26],q[500001],point[500001],danger[500001];bool mark[500001];inline void ins(){    int now=1,l=strlen(s);    for (int i=0;i<l;i++)    {        int x=s[i]-'a';        if (!a[now][x])a[now][x]=++tot;        now=a[now][x];    }    danger[now]++;}inline void acmach(){    int Head=0,tail=1,now;    q[1]=1;point[1]=0;      while (Head!=tail)    {        now=q[++Head];        for (int i=0;i<26;i++)        {            if (!a[now][i]) continue;            int k=point[now];            while (!a[k][i])k=point[k];            point[a[now][i]]=a[k][i];            q[++tail]=a[now][i];        }    }}inline void solve(){    int now=1,l=strlen(m);    for (int i=0;i<l;i++)    {        mark[now]=1;        int x=m[i]-'a';        while (!a[now][x])now=point[now];        now=a[now][x];        if (!mark[now])            for (int j=now;j;j=point[j])            {                ans+=danger[j];                danger[j]=0;            }    }    printf("%d\n",ans);}int main(){    for (int i=0;i<26;i++)a[0][i]=1;    int Case=read();    while (Case--)    {        n=read();tot=1;ans=0;        while (n--)        {            scanf("%s",s);            ins();        }        acmach();        scanf("%s",m);        solve();        for(int i=1;i<=tot;i++)        {            point[i]=danger[i]=mark[i]=0;            for(int j=0;j<26;j++)                a[i][j]=0;        }    }    return 0;}
原创粉丝点击