Advertisement
Malinovsky239

suffix automata

May 28th, 2012
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <iostream>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. const int N = int(1e5 + 5);
  9.  
  10. struct node {
  11.     int suf;
  12.     int to[26];    
  13. };
  14.  
  15. node au[N];
  16. int end, cnt, new_end, dp[N];
  17. char s[N];
  18.  
  19. int main() {
  20.     gets(s);
  21.  
  22.     int l = strlen(s);
  23.  
  24.     for (int i = 0; i < l; i++) {
  25.         cnt++;
  26.         new_end = cnt;
  27.  
  28.         int sym = s[i] - 'a';
  29.        
  30.         au[end].to[sym] = new_end;
  31.         dp[new_end] = dp[end] + 1;
  32.  
  33.         int now = end;
  34.         while (now) {
  35.             now = au[now].suf;
  36.  
  37.             if (au[now].to[sym]) {
  38.  
  39.                 int nxt = au[now].to[sym];
  40.                 if (dp[nxt] == dp[now] + 1) {
  41.                     au[new_end].suf = nxt;
  42.                 }
  43.                 else {
  44.                     cnt++;
  45.                     au[nxt].suf = cnt;
  46.                     dp[cnt] = dp[now] + 1;
  47.                    
  48.                     for (int j = 0; j < 26; j++)
  49.                         if (au[nxt].to[j])
  50.                             au[cnt].to[j] = au[nxt].to[j];
  51.  
  52.                     while (now) {
  53.                         now = au[now].suf;
  54.                         if (au[now].to[sym] == nxt)
  55.                             au[now].to[sym] = cnt;                         
  56.                     }
  57.                 }
  58.  
  59.                 break; 
  60.             }
  61.             else {
  62.                 au[now].to[sym] = new_end;
  63.                 dp[new_end] = max(dp[end], dp[now] + 1);
  64.             }
  65.         }
  66.         end = new_end;
  67.     }
  68.  
  69.     for (int i = 0; i <= cnt; i++) {
  70.         for (int j = 0; j < 26; j++)
  71.             if (au[i].to[j]) {
  72.                 printf("edge %d-%d through %c\n", i, au[i].to[j], 'a' + j);
  73.             }
  74.     }  
  75.  
  76.     for (int i = 0; i <= cnt; i++)  
  77.         printf("suf[%d] = %d\n", i, au[i].suf);
  78.    
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement