【AC自动机】HDU 2222 Keywords Search

题目链接

Keywords Search

题目

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

题意

给定n个模式串和一个主串,求在主串中有多少个模式串。

分析

AC自动机模板题。
需要注意的是hdu oj上g++与c++的不同,这里代码提交g++能ac,但提交c++会超时。

AC代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

const int maxn=1e6+100;
int child[maxn][26];
int fail[maxn];
int tot,sta[maxn];

void init()
{
    tot=0;
    memset(child,-1,sizeof(child));
    memset(fail,0,sizeof(fail));
    memset(sta,0,sizeof(sta));
}
void Insert(char *s)
{
    int p=0,len=strlen(s);
    for(int i=0;i<len;i++)
    {
        int v=s[i]-'a';
        if(child[p][v]==-1)
            child[p][v]=++tot;
        p=child[p][v];
    }
    sta[p]++;
}
void build()
{
    queue<int> que;
    while(!que.empty()) que.pop();
    for(int i=0;i<26;i++)
    {
        if(child[0][i]==-1)
            child[0][i]=0;
        else
        {
            que.push(child[0][i]);
        }
    }
    while(!que.empty())
    {
        int p=que.front();que.pop();
        int nxt=fail[p];
        for(int i=0;i<26;i++)
        {
            int &c=child[p][i];
            if(c==-1)
                c=child[nxt][i];
            else
            {
                fail[c]=child[nxt][i];
                que.push(c);
            }
        }
    }
}
int solve(char *s)
{
    int p=0,len=strlen(s),ans=0;
    for(int i=0;i<len;i++)
    {
        int v=s[i]-'a';
        p=child[p][v];
        int tmp=p;
        while(tmp)
        {
            ans+=sta[tmp];
            sta[tmp]=0;
            tmp=fail[tmp];
        }
    }
    return ans;
}
char str[maxn];
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n;
        init();
        scanf("%d",&n);
        while(n--)
        {
            scanf("%s",str);
            Insert(str);
        }
        build();
        scanf("%s",str);
        printf("%d\n",solve(str));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37685156/article/details/80255896