Advertisement
dipBRUR

Suffix Automaton Implementation

Aug 17th, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. /**
  2.  * Author          : Dipu Kumar Mohanto Dip
  3.  *                   CSE, BRUR.
  4.  *                   Batch - 6
  5.  *
  6.  * Problem         : Suffix Automaton Implementation
  7.  * Algorithm       : SAM - Suffix Automaton
  8.  * Complexity      : O(n)
  9.  * Category        : String
  10.  *
  11.  * Difficulty      : Hard
  12.  *
  13.  * Source          : sai sumit
  14.  *                   E-max algo
  15.  *
  16.  * Verdict         : OK
  17.  *
  18.  * Date            :
  19.  * E-mail          : dipukumarmohanto1@gmail.com
  20. **/
  21.  
  22.  
  23. #include <bits/stdc++.h>
  24.  
  25. using namespace std;
  26.  
  27.  
  28.  
  29. struct state {
  30.     int len, link;
  31.     map <char, int> next;
  32. };
  33.  
  34. const int mx = 1e6+5;
  35.  
  36. state st[mx<<1];
  37. int sz, last;
  38.  
  39. void init()
  40. {
  41.     sz = last = 0;
  42.     st[0].len = 0;
  43.     st[0].link = -1;
  44.     ++sz;
  45.    
  46.     //clear the structure
  47.     //for (int i=0; i<(mx<<1); i++)
  48.     //{
  49.     //    st[i].next.clear();
  50.     //}
  51. }
  52.  
  53.  
  54.  
  55. void sz_extend(char c)
  56. {
  57.     int curr = sz++;
  58.    
  59.     st[curr].len = st[last].len + 1;
  60.    
  61.     int p;
  62.    
  63.     for (p=last; p != -1 && !st[p].next.count(c); p = st[p].link)
  64.         st[p].next[c] = curr;
  65.        
  66.     if (p == -1)
  67.         st[curr].link = 0;
  68.    
  69.     else
  70.     {
  71.         int q = st[p].next[c];
  72.        
  73.         if (st[p].len + 1 == st[q].len)
  74.             st[curr].link = q;
  75.        
  76.         else
  77.         {
  78.             int clone = sz++;
  79.            
  80.             st[clone].len = st[p].len + 1;
  81.             st[clone].next = st[q].next;
  82.             st[clone].link = st[q].link;
  83.            
  84.             for ( ; p!=-1 && st[p].next[c] == q; p = st[p].link)
  85.                 st[p].next[c] = clone;
  86.            
  87.             st[q].link = st[curr].link = clone;
  88.         }
  89.     }
  90.     last = curr;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement