HDU 2222 Keywords Search(AC自动机)

来源:互联网 发布:sql server删除多个表 编辑:程序博客网 时间:2024/04/30 18:44

Description
求文本串中出现了几次模式串
Input
第一行为用例组数T,每组用例第一行为一个整数n表示模式串个数,最后一行为文本串
Output
输出文本串中模式串出现次数
Sample Input
1
5
she
he
say
shr
her
yasherhs
Sample Output
3
Solution
AC自动机裸题
Code

#include<cstdio>#include<algorithm>#include<iostream>#include<cstring>#include<queue>using namespace std;#define maxn 55#define maxl 11111struct Trie{    int next[maxn*maxl][26],fail[maxn*maxl],end[maxn*maxl];    int root,L;    int newnode()    {        for(int i=0;i<26;i++)            next[L][i]=-1;        end[L++]=0;        return L-1;    }    void init()    {        L=0;        root=newnode();    }    void insert(char buf[])    {        int len=strlen(buf);        int now=root;        for(int i=0;i<len;i++)        {            if(next[now][buf[i]-'a']==-1)                next[now][buf[i]-'a']=newnode();            now=next[now][buf[i]-'a'];        }        end[now]++;    }    void build()    {        queue<int>Q;        fail[root]=root;        for(int i=0;i<26;i++)            if(next[root][i]==-1)                next[root][i]=root;            else            {                fail[next[root][i]]=root;                Q.push(next[root][i]);            }        while(!Q.empty())        {            int now=Q.front();            Q.pop();            for(int i=0;i<26;i++)                if(next[now][i]==-1)                    next[now][i]=next[fail[now]][i];                else                {                    fail[next[now][i]]=next[fail[now]][i];                    Q.push(next[now][i]);                }        }    }    int query(char buf[])    {        int len=strlen(buf);        int now=root;        int res=0;        for(int i=0;i<len;i++)        {            now=next[now][buf[i]-'a'];            int temp=now;            while(temp!=root)            {                res+=end[temp];                end[temp]=0;                temp=fail[temp];            }        }        return res;    }};char buf[1111111];Trie ac;int main(){    int T;    int n;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        ac.init();//初始化         for(int i=0;i<n;i++)        {            scanf("%s",buf);            ac.insert(buf);//插入模式串         }        ac.build();//建树         scanf("%s",buf);        printf("%d\n",ac.query(buf));    }    return 0;}
0 0
原创粉丝点击