zoukankan      html  css  js  c++  java
  • HDU2222 Keywords Search(AC自动机模版题)

    邝斌大神的模版mark一下

    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cmath>
    #include <queue>
    #include <vector>
    #include <cstdio>
    using namespace std;
    struct Trie
    {
        int next[500010][26],fail[500010],end[500010];
        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[1000010];
    Trie ac;
    int main()
    {
        //freopen("in.txt","r",stdin);
        int t,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
    ",ac.query(buf));
        }
        return 0;
    }
  • 相关阅读:
    对象实例化过程分析
    对象实例化过程分析
    QuickHit游戏
    QuickHit游戏
    java继承向上转型和向下转型和动态绑定
    java继承向上转型和向下转型和动态绑定
    洛谷:P1095 守望者的逃离(贪心+dp)
    Manacher算法-最长回文子串
    numpy array()
    CNN 卷积神经网络结构
  • 原文地址:https://www.cnblogs.com/d-e-v-i-l/p/4867751.html
Copyright © 2011-2022 走看看