zoukankan      html  css  js  c++  java
  • [AC自动机模板]Keywords Search

    只是记录一下代码

    AC自动机算法的教程请移步这里

    还有这里

    指针看着懵逼的还可以看一下这里

    #include<iostream>
    #include<cstdio>
    #include<queue>
    #include<cstring>
    #define maxn 10010
    #define maxl 1000100
    using namespace std;
    int n;
    char s[maxl];
    struct ac_automation
    {
        int tot;
        struct node
        {
            node *son[26];//记录儿子
            int size;//儿子数
            node *fail;//失配指针
            node ()
            {
                memset(this,0,sizeof(node));
            }
        };
        node *root;
        inline void init()
        {
            root=new node();
        }
        inline void insert()
        {
            int l=strlen(s+1),i=1;
            node *now=root;
            while(i<=l)
            {
                if(!now->son[s[i]-'a'])now->son[s[i]-'a']=new node();
                now=now->son[s[i]-'a'];
                i++;
            }
            now->size++;
        }
        inline void build()
        {
            queue <node*> q;
            for(int i=0;i<26;i++)
            {
                if(root->son[i])
                {
                    q.push(root->son[i]);
                    root->son[i]->fail=root;
                }
                else root->son[i]=root;
            }
            while(!q.empty())
            {
                node *x=q.front();
                q.pop();
                for(int i=0;i<26;i++)
                {
                    if(x->son[i])
                    {
                        x->son[i]->fail=x->fail->son[i];
                        q.push(x->son[i]);
                    }
                    else x->son[i]=x->fail->son[i];
                }
            }
        }
        inline int query()
        {
            node *now=root;
            int i=1,l=strlen(s+1),ans=0;
            while(i<=l)
            {
                now=now->son[s[i]-'a'];
                for(node *j=now;j!=root&&j->size!=-1;j=j->fail)
                {
                    ans+=j->size;
                    j->size=-1;
                }
                i++;
            }
            return ans;
        }
    }ac;
    int main()
    {
        int t;
        scanf("%d",&t);
        while(t--)
        {
            ac.init();//千万别忘了
            scanf("%d",&n);
            for(int i=1;i<=n;i++)
            {
                scanf("%s",s+1);
                ac.insert();
            }
            ac.build();
            scanf("%s",s+1);
            printf("%d
    ",ac.query());
        }
        return 0;
    }
  • 相关阅读:
    转 无障碍阅读 role aria-*
    (转)edm注意事项
    Spring IOC机制之使用注解配置bean
    Spring IOC机制使用SpEL
    使用Spring IOC容器引用外部属性文件
    如何将属性文件中的值保存到类中
    基于XML的类的属性的装配
    Java——事务
    Eclipse中使用Spring IOC容器的具体方法
    Java之批处理的实现
  • 原文地址:https://www.cnblogs.com/Rorschach-XR/p/11021881.html
Copyright © 2011-2022 走看看