Advertisement
dipBRUR

Longest Common Substring for multiple string

Aug 25th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ada 1.54 KB | None | 0 0
  1. 8. Longest Common Substring for multiple string :
  2.                                                 Same idea as we used to calculate
  3.    LCS of two string. Just add w(final minimum matching of the state) and
  4.    v(maximum matching of the state of current two string).
  5.  
  6. Expected Complexity : O(sum(all string)*k), k = total string
  7.  
  8. const int inf = 1 << 28;
  9. struct state {
  10.     int len;
  11.     int link;
  12.     int w;
  13.     int v;
  14.     int pos;   // to print the string
  15.     map <char, int> next;  // when cause TLE, use array instead of map
  16.    
  17.     node() {}
  18.  
  19.     node() {
  20.         len = 0;
  21.         link = -1;
  22.         w = inf;
  23.         v = 0;
  24.         pos = -1;
  25.         next.clear();
  26.     }
  27. } st[mx << 1];
  28.  
  29. // construct suffix automata
  30. int tNode;
  31. void buildDFA(string s, int len)
  32. {
  33.     init();
  34.     for (int i=0; i<len; i++)
  35.         sz_extend(s[i]);
  36.     tNode = sz;
  37. }
  38.  
  39. void LCS(string t, int len)
  40. {
  41.     int v = 0;  // initial state
  42.     int l = 0;  // initial match
  43.  
  44.     for (int i=0; i<len; i++)
  45.     {
  46.         char c = t[i];
  47.         while (v && !st[v].next.count(c))
  48.         {
  49.             v = st[v].link;
  50.             l = st[v].len;
  51.         }
  52.         if (st[v].next.count(c))
  53.         {
  54.             v = st[v].next[c];
  55.             l++;
  56.         }
  57.         st[v].v = max(st[v].v, l);
  58.     }
  59.     for (int i=1; i<tNode; i++)
  60.         st[st[i].link].v = max(st[st[i].link].v, st[i].v);  // copy to root
  61.     for (int i=0; i<tNode; i++)
  62.     {
  63.         st[i].w = min(st[i].w, st[i].v);
  64.         st[i].v = 0;
  65.     }
  66. }
  67.  
  68. void get_final_len()
  69. {  
  70.     int res = -1;
  71.     for (int i=0; i<tNode; i++)
  72.         res = max(res, min(st[i].len, st[i].w);
  73.     cout << "LCS : " << res << endl;
  74. }
  75.  
  76. Practice Problem :
  77.                  Spoj   : LCS2 - Longest Common Substring II
  78.                  UVA-LA : 3451 - Longest Common Substring
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement