Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. namespace aho {
  2.     const int N = 4000000, C = 2;
  3.     int trans[N][C];
  4.     int lst = 1;
  5.     int fail[N];
  6.     int term[N];
  7.  
  8.     void build(const vector<string> &v) {
  9.         rep(i, sz(v)) {
  10.             int s = 0;
  11.             repi(j, v[i]) {
  12.                 int &t = trans[s][j=='o'];
  13.                 if (!t) t = lst++;
  14.                 s = t;
  15.             }
  16.             term[s] = i+1;
  17.         }
  18.  
  19.         queue<int> q; rep(i, C) if (trans[0][i]) q.push(trans[0][i]);
  20.         while(sz(q) > 0) {
  21.             int t = q.front(); q.pop();
  22.             rep(i, C) if (trans[t][i]) {
  23.                 int p = fail[t];
  24.                 while(p and !trans[p][i]) p = fail[p];
  25.                 p = trans[p][i];
  26.                 fail[trans[t][i]] = p;
  27.                 assert(term[p] == 0);
  28.                 q.push(trans[t][i]);
  29.             }
  30.         }
  31.     }
  32.  
  33.     bool query(string &s){
  34.         int p = 0;
  35.         for(auto &i : s){
  36.             while(p and !trans[p][i]) p = fail[p];
  37.             p = trie[p][i];
  38.             if(term[p]) return 1;
  39.         }
  40.         return 0;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement