hihoCoder #1036 Trie图

传送门 http://hihocoder.com/problemset/problem/1036

Solution:

  1 #include <iostream>
  2 #include <cstring>
  3 #include <queue>
  4 #include <cstdio>
  5 using namespace std;
  6 
  7 struct Node 
  8 {
  9     int par;
 10     int key;
 11     int pos;
 12     int next[26];
 13     int end;
 14 };
 15 
 16 Node* trie[1000001] = {0};
 17 int K = 0;
 18 int sfx[1000001];
 19 
 20 Node *createNode(char ch)
 21 {
 22     Node *p = new Node();
 23     p->key = ch - 'a';
 24     p->par = 0;
 25     p->pos = K;
 26     p->end = 0;
 27     trie[K++] = p;
 28     memset(p->next, -1, sizeof p->next);
 29     return p;
 30 }
 31 
 32 void addWord(const char *word)
 33 {
 34     Node *level = trie[0];
 35     const char *p = word;
 36     while (*p) {
 37         int k = *p-'a';
 38         if (level->next[k] == -1) {
 39             Node *n = createNode(*p);
 40             n->par = level->pos;
 41             level->next[k] = n->pos;
 42         }
 43     
 44         level = trie[level->next[k]];
 45         p++;
 46         if (*p == '\0') level->end = 1;
 47     }
 48 }
 49 
 50 int suffix(int n)
 51 {
 52     if (sfx[n] >= 0) return sfx[n];
 53     if (n == 0 || trie[n]->par == 0) return sfx[n] = 0;
 54     else {
 55         int par = trie[n]->par;
 56         int key = trie[n]->key;
 57         return sfx[n] = trie[suffix(par)]->next[key];
 58     }
 59 }
 60 
 61 void preProcess()
 62 {
 63     memset(sfx, -1, sizeof sfx);
 64     queue<int> que;
 65     que.push(0);
 66     while (!que.empty()) {
 67         int n = que.front();
 68         que.pop();
 69         Node *p = trie[n];
 70         int s = suffix(n);
 71         for (int i = 0; i < 26; ++i) {
 72             if (p->next[i] != -1) {
 73                 que.push(p->next[i]);
 74             } 
 75             else p->next[i] = s ? trie[s]->next[i] : 0;            
 76         }
 77     }
 78 }
 79 
 80 
 81 bool query(const char *t)
 82 {
 83     int p = 0;
 84     while (*t) {
 85         p = trie[p]->next[*t - 'a'];
 86         if (trie[p]->end) return true;
 87         t++; 
 88     }
 89     return false;
 90 }
 91 
 92 
 93 void destory()
 94 {
 95     for (int i = 0; i < K; ++i) {
 96         delete trie[i];
 97     }
 98 }
 99 
100 int main()
101 {
102     Node *root = createNode('\0');
103     int N;
104     cin >> N;
105     char word[1000001];
106     for (int i = 0; i < N; ++i) {
107         scanf("%s", word);
108         addWord(word);
109     }
110 
111     char text[1000001];
112     scanf("%s", text);
113 
114     preProcess();
115 
116     if (query(text)) {
117         cout << "YES" << endl;
118     }
119     else cout << "NO" << endl;
120 
121     destory();
122 
123 }

 

posted @ 2015-03-19 20:53  HaruHaru  阅读(155)  评论(0编辑  收藏  举报