hihoCoder--1036 Trie图(AC自动机)

problem link

题解

#include <bits/stdc++.h>
using namespace std;

const int maxn = 26;
const int maxn_node = 500010;

struct Node{
    Node* next[maxn];
    Node* fail;
    int cnt;
    Node(){
        fail = NULL;
        cnt = 0;
        memset(next, 0, sizeof(next));
    }
};

void build_trie(string s, Node* root){
    for(int i = 0; i < s.length(); ++i){
        int id = s[i] - 'a';
        if(!root->next[id]) root->next[id] = new Node();
        root = root->next[id];
    }
    root->cnt++;
}

void build_fail(Node* root){
    root->fail = NULL;
    queue<Node*> Q;
    Q.push(root);
    while(!Q.empty()){
        Node* cur = Q.front(); Q.pop();
        for(int i = 0; i < maxn; ++i){
            if(cur->next[i]){
                if(cur == root){
                    cur->next[i]->fail = root;
                }else{
                    Node* p = cur->fail;
                    while(p){
                        if(p->next[i]){
                            cur->next[i]->fail = p->next[i];
                            break;
                        }
                        p = p->fail;
                    }
                    if(p == NULL){
                        cur->next[i]->fail = root;
                    }
                }
                Q.push(cur->next[i]);
            }
        }

    }
}

bool query(string text, Node* root){
    Node* p = root;
    int cnt = 0;
    for(int i = 0; i < text.length(); ++i){
        int id = text[i] - 'a';
        while(p->next[id] == NULL && p != root) p = p->fail;
        p = p->next[id];
        if(p == NULL) p = root;
        Node* tmp = p;
        while(tmp != root && tmp->cnt != -1){
            cnt += tmp->cnt;
            tmp->cnt = -1;
            tmp = tmp->fail;
        }
    }

    return cnt > 0;
}


int main(){
#ifdef EXMY
freopen("data.in", "r", stdin);
#endif // EXMY
    int n;
    string s, text;
    Node* root = new Node();
    cin >> n;
    while(n--){
        cin >> s;
        build_trie(s, root);
    }
    build_fail(root);
    cin >> text;
    if(query(text, root)) cout << "YES" << endl;
    else cout << "NO" << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值