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

来源:互联网 发布:如何申请网络域名 编辑:程序博客网 时间:2024/05/16 00:33

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 EXMYfreopen("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