• hihoCoder week4 Trie图


    ac自动机 

    题目链接 https://hihocoder.com/contest/hiho4/problem/1

    参考:https://blog.csdn.net/baidu_30541191/article/details/47447175#

    #include <iostream>
    #include <cstring>
    #include <string>
    #include <queue>
    using namespace std;
    
    struct node 
    {
        node *nxt[26], *fail;
        int ok; 
        node() {
            ok = 0;
            for(int i=0; i<26; i++) nxt[i]=NULL;
            fail=NULL;
        }
    };
    
    const int N = 1e6 + 10;
    char s[N]; 
    node *root;
    
    void ins(char *s, int len) 
    {
        node *rt = root;
        for(int i=0; i<len; i++) {
            int x= s[i]-'a';
            if(rt->nxt[x] == NULL)
                rt->nxt[x] = new node();
            rt= rt->nxt[x];
        }
        rt->ok = 1;
        return ;
    }
    
    void build()
    {
        node *rt = root;
        rt->fail = NULL;
        
        queue<node*> que;
        que.push(rt);
        
        while(!que.empty()) {
            node *tmp = que.front();
            que.pop();
            for(int i=0; i<26; i++) {
                if(tmp->nxt[i] != NULL) {
                    if(tmp == root) 
                        tmp->nxt[i]->fail = root;
                    else {
                        node *p = tmp->fail;
                        while(p!=NULL) {
                            if(p->nxt[i] != NULL) {
                                tmp->nxt[i]->fail = p->nxt[i];
                                break;
                            }
                            p = p->fail;
                        }
                        if(p==NULL) tmp->nxt[i]->fail = root;
                    }
                    que.push(tmp->nxt[i]);
                }
            }
        }
    }
    
    bool query(char *s, int len)
    {
        node *rt = root;
        int cnt=0;
        for(int i=0; i<len; i++) {
            int x = s[i]-'a';
            while(!rt->nxt[x] && rt->fail != NULL) 
                rt=rt->fail;
            rt=rt->nxt[x];
            if(!rt) rt = root;
            node * tmp = rt;
            while(tmp->ok==1) {
                cnt++;
                tmp->ok = 0;
                tmp = tmp->fail;
            }
        }
        if(cnt > 0)
            return true;
        return false;
    }
    
    
    int main()
    {
        root = new node();
        int n; scanf("%d",&n);
        for(int i=0; i<n; i++) {
            scanf("%s", s), ins(s, strlen(s));
        }
            
        build();
        scanf("%s", s);
        bool ok = query(s,strlen(s));
        if(ok) 
            cout<<"YES"<<endl;
        else 
            cout<<"NO"<<endl;
        return 0;
    }
  • 相关阅读:
    javascript对象继承的实现
    浏览器兼容问题汇总<转>
    DOM笔记
    Ajax日记
    学习态度
    项目1
    导航项目-整体布局
    有关布局
    导航项目开始
    windows 服务 定时程序 跑不出数据
  • 原文地址:https://www.cnblogs.com/Draymonder/p/9918322.html
Copyright © 2020-2023  润新知