zoukankan      html  css  js  c++  java
  • hihocoder 1036 Trie图

    url: http://hihocoder.com/problemset/problem/1036

    #include<cstdio>
    #include<cstdlib>
    #include<queue>
    #include<cstring>
    using namespace std;
    const int max_node=1e6+5,sigma_size=26;
    char s[1000005];
    struct AhoCorasickAutomata
    {
        int ch[max_node][sigma_size],fail[max_node],sz;
        bool val[max_node];
        inline void init()
        {
            sz=1;
            memset(ch[0],0,sizeof(ch[0]));
        }
        inline int idx(char c){return c-'a';}
        void Insert(char *s)
        {
            int u=0,len=strlen(s);
            for(int i=0;i<len;i++)
            {
                int c=idx(s[i]);
                if(!ch[u][c])
                {
                    memset(ch[sz],0,sizeof(ch[sz]));
                    val[sz]=0;
                    ch[u][c]=sz++;
                }
                u=ch[u][c];
            }
            val[u]=1;
        }
        void Getfail()
        {
            queue<int>q;
            for(int i=0;i<sigma_size;i++)
            {
                int u=ch[0][i];
                if(u){fail[u]=0;q.push(u);}
            }
            while(!q.empty())
            {
                int r=q.front();q.pop();
                for(int i=0;i<sigma_size;i++)
                {
                    int u=ch[r][i];
                    if(!u){ch[r][i]=ch[fail[r]][i];continue;}
                    q.push(u);
                    int v=fail[r];
                    while(v&&!ch[v][i])v=fail[v];
                    fail[u]=ch[v][i];
                }
            }
        }
        bool Find(char* s)
        {
            for(int i=0,j=0;s[i];i++)
            {
                int c=idx(s[i]);
                j=ch[j][c];
                if(val[j])return 1;
            }
            return 0;
        }
    }ac;
    int main()
    {
        ac.init();
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%s",s);
            ac.Insert(s);
        }
        ac.Getfail();
        scanf("%s",s);
        puts(ac.Find(s)?"YES":"NO");
        return 0;
    }
  • 相关阅读:
    转:ORA-12541:TNS:无监听程序问题
    实战jmeter入门压测接口性能
    数据库的4种常用设计模式
    三范式,数据库设计的基本准则
    html5学习2
    html5学习1
    php初写成
    Typora编辑区域空白过大问题
    CURL 常用命令
    阿里云镜像创建Spring Boot工厂
  • 原文地址:https://www.cnblogs.com/homura/p/6482651.html
Copyright © 2011-2022 走看看