Advertisement
Manioc

story

Feb 5th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAX 500007
  3.  
  4. using namespace std;
  5.  
  6. int link[MAX], len[MAX], tab[MAX][26], sz, last;
  7. string s, t;
  8.  
  9. void init(){
  10.     link[0] = -1;
  11.     len[0] = 0;
  12.     sz = 1;
  13.     last = 0;
  14. }
  15.  
  16. void extend(int c){
  17.     int cur = sz++;
  18.     len[cur] = len[last] +1;
  19.     for(; last != -1 && !tab[last][c]; last = link[last]) tab[last][c] = cur;
  20.  
  21.     if(last != -1){
  22.         int p = tab[last][c];
  23.         if(len[p] == len[last] + 1) link[cur] = p;
  24.         else{
  25.             int clone = sz++;
  26.             len[clone] = len[last] + 1;
  27.             memcpy(tab[p], tab[clone], sizeof tab[clone]);
  28.             link[clone] = link[p];
  29.             for(;last != -1 && tab[last][c] == p; last = link[last]) tab[last][c] = clone;
  30.             link[p] = link[cur] = clone;
  31.         }
  32.     }else link[cur] = 0;
  33.     last = cur;
  34. }
  35.  
  36. void substring(){
  37.     init();
  38.     for(int i = 0; i < s.size(); i++) extend(s[i]-'a');
  39.  
  40.     int estado = 0, tamanho = 0, maior = 0, melhor = 0;
  41.     for(int i = 0; i < t.size(); i++){
  42.         while(estado && !tab[estado][t[i]-'a']){
  43.             estado = link[estado];
  44.             tamanho = len[estado];
  45.         }
  46.  
  47.         if(tab[estado][t[i]-'a']){
  48.             estado = tab[estado][t[i]-'a'];
  49.             tamanho++;
  50.         }
  51.  
  52.         if(tamanho > maior){
  53.             maior = tamanho;
  54.             melhor = i;
  55.         }
  56.     }
  57.     if(maior > 0) cout << t.substr(melhor-maior+1, maior) << endl;
  58.     cout << maior << endl;
  59. }
  60.  
  61. int main(){
  62.     cin >> s >> t;
  63.     substring();
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement