Madiyar

Ахо Корасик

Nov 13th, 2012
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <cstdio>
  5. using namespace std;
  6.  
  7. struct state {
  8.     int next[2];
  9.     int end,suff;
  10. } st[500000];
  11. int sz,n,u[500000],to[500000][2],q[500000];
  12. string s;
  13.  
  14. void Dfs(int v)
  15. {
  16.     u[v] = 1;
  17.  
  18.     for (int i = 0; i < 2; ++i)
  19.     if (!st[to[v][i]].end) {
  20.         if (u[to[v][i]] == 1) {
  21.             puts("TAK");
  22.             exit(0);
  23.         }
  24.         if (!u[to[v][i]])
  25.             Dfs(to[v][i]); 
  26.  
  27.     }
  28.     u[v] = 2;
  29. }
  30.        
  31. int main()
  32. {
  33.     freopen("input.txt","r",stdin);
  34.     freopen("output.txt","w",stdout);
  35.    
  36.     memset(st[0].next,-1,sizeof(st[0].next));
  37.     st[0].suff = -1;
  38.     st[0].end = 0;
  39.  
  40.     sz = 1;
  41.  
  42.     cin>>n;
  43.     for (int i = 0; i < n; ++i) {
  44.         cin>>s;
  45.        
  46.  
  47.         int cur = 0;
  48.  
  49.  
  50.         for (int j = 0; j < s.size(); ++j) {
  51.             if (st[cur].next[s[j]-'0'] == -1) {
  52.                 memset(st[sz].next,-1,sizeof(st[sz].next));
  53.                 st[sz].end = false;
  54.                 st[cur].next[s[j]-'0'] = sz++;
  55.             }
  56.                         cur = st[cur].next[s[j]-'0'];
  57.         }
  58.         st[cur].end = true;
  59.     }
  60.    
  61.     int head = 0, tail = 0;
  62.  
  63.     q[tail++] = 0;
  64.  
  65.     while (head != tail) {
  66.         int cur = q[head++];
  67.  
  68.         for (int i = 0; i < 2; ++i)
  69.             if (st[cur].next[i] != -1) to[cur][i] = st[cur].next[i]; else
  70.             if (cur > 0) to[cur][i] = to[st[cur].suff][i]; else
  71.             to[cur][i] = cur;
  72.  
  73.         for (int i = 0; i < 2; ++i)
  74.         if (st[cur].next[i] != -1) {
  75.             int v = st[cur].next[i];
  76.             q[tail++] = v;
  77.  
  78.             int p = st[cur].suff;
  79.             for (;p != -1 && st[p].next[i] == -1; p = st[p].suff);
  80.  
  81.             if (p == -1) st[v].suff = 0; else
  82.             st[v].suff = st[p].next[i];
  83.  
  84.             st[v].end |= st[st[v].suff].end;
  85.         }
  86.     }
  87.  
  88.     Dfs(0);
  89.     puts("NIE");
  90.     return 0;
  91.  
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment