Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 8. Longest Common Substring for multiple string :
- Same idea as we used to calculate
- LCS of two string. Just add w(final minimum matching of the state) and
- v(maximum matching of the state of current two string).
- Expected Complexity : O(sum(all string)*k), k = total string
- const int inf = 1 << 28;
- struct state {
- int len;
- int link;
- int w;
- int v;
- int pos; // to print the string
- map <char, int> next; // when cause TLE, use array instead of map
- node() {}
- node() {
- len = 0;
- link = -1;
- w = inf;
- v = 0;
- pos = -1;
- next.clear();
- }
- } st[mx << 1];
- // construct suffix automata
- int tNode;
- void buildDFA(string s, int len)
- {
- init();
- for (int i=0; i<len; i++)
- sz_extend(s[i]);
- tNode = sz;
- }
- void LCS(string t, int len)
- {
- int v = 0; // initial state
- int l = 0; // initial match
- for (int i=0; i<len; i++)
- {
- char c = t[i];
- while (v && !st[v].next.count(c))
- {
- v = st[v].link;
- l = st[v].len;
- }
- if (st[v].next.count(c))
- {
- v = st[v].next[c];
- l++;
- }
- st[v].v = max(st[v].v, l);
- }
- for (int i=1; i<tNode; i++)
- st[st[i].link].v = max(st[st[i].link].v, st[i].v); // copy to root
- for (int i=0; i<tNode; i++)
- {
- st[i].w = min(st[i].w, st[i].v);
- st[i].v = 0;
- }
- }
- void get_final_len()
- {
- int res = -1;
- for (int i=0; i<tNode; i++)
- res = max(res, min(st[i].len, st[i].w);
- cout << "LCS : " << res << endl;
- }
- Practice Problem :
- Spoj : LCS2 - Longest Common Substring II
- UVA-LA : 3451 - Longest Common Substring
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement