Advertisement
slash0t

aho corasik

Dec 25th, 2024 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. struct aho_corasik {
  2.     const static int alphabet = 26;
  3.     const static char al_start = 'a';
  4.  
  5.     struct node {
  6.         node* sufflink = nullptr;
  7.         char from_char;
  8.         node* parent;
  9.         node* to[alphabet];
  10.         node* go[alphabet];
  11.         int terminal = 0;
  12.  
  13.         node(char from, node* par) : from_char(from), parent(par) {
  14.             memset(to, 0, sizeof(to));
  15.             memset(go, 0, sizeof(go));
  16.         }
  17.     };
  18.  
  19.     node* root = new node(0, nullptr);
  20.  
  21.     node* get_go(node* now, char to) {
  22.         to -= al_start;
  23.         if (now->go[to]) return now->go[to];
  24.         if (now->to[to]) now->go[to] = now->to[to];
  25.         if (now == root && !now->to[to]) now->go[to] = root;
  26.         if (!now->go[to]) {
  27.             now->go[to] = get_go(get_sufflink(now), to + al_start);
  28.         }
  29.         return now->go[to];
  30.     }
  31.  
  32.     node* get_sufflink(node* now) {
  33.         if (now->sufflink) return now->sufflink;
  34.         if (now == root || now->parent == root) now->sufflink = root;
  35.         if (!now->sufflink) {
  36.             now->sufflink = get_go(get_sufflink(now->parent), now->from_char);
  37.         }
  38.         return now->sufflink;
  39.     }
  40.  
  41.     node* add(string& s) {
  42.         node* now = root;
  43.         for (char c : s) {
  44.             c -= al_start;
  45.             if (!now->to[c]) now->to[c] = new node(c + al_start, now);
  46.             now = now->to[c];
  47.         }
  48.         now->terminal = 1;
  49.         return now;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement