The longest common substring of multiple strings and the smallest Lexicographic Order is output.
Question: suffix array, two answers.
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <string>
# Include <queue>
# Include <algorithm>
# Include <vector>
# Include <stack>
# Include <list>
# Include <iostream>
# Include <map>
Using namespace std;
# Define inf 0x3f3f3f
# Define M 810000
Int max (int a, int B)
{
Return a> B? A: B;
}
Int min (int a, int B)
{
Return a <B? A: B;
}
Int height [M], rank [M], r [M], sa [M];
Int ts [M], ta [M], tb [M], TV [M], pos [M], st, ed;
Int rec [10000], flag [10000];
Bool cmp (int * y, int a, int B, int l)
{
Return y [a] = y [B] & y [a + l] = y [B + l];
}
Void da (int n, int m)
{
Int I, j, * x = ta, * y = tb, p;
For (I = 0; I <m; I ++) ts [I] = 0;
For (I = 0; I <n; I ++) ts [x [I] = r [I] ++;
For (I = 1; I <m; I ++) ts [I] + = ts [I-1];
For (I = n-1; I> = 0; I --) sa [-- ts [x [I] = I;
For (j = 1, p = 1; p <n; j * = 2, m = p)
{
P = 0;
For (I = n-j; I <n; I ++) y [p ++] = I;
For (I = 0; I <n; I ++) if (sa [I]> = j) y [p ++] = sa [I]-j;
For (I = 0; I <m; I ++) ts [I] = 0;
For (I = 0; I <n; I ++) TV [I] = x [y [I];
For (I = 0; I <n; I ++) ts [TV [I] ++;
For (I = 1; I <m; I ++) ts [I] + = ts [I-1];
For (I = n-1; I> = 0; I --) sa [-- ts [TV [I] = y [I];
Swap (x, y );
X [sa [0] = 0;
P = 1;
For (I = 1; I <n; I ++)
{
If (cmp (y, sa [I-1], sa [I], j) x [sa [I] = p-1;
Else x [sa [I] = p ++;
}
}
}
Void calh (int n)
{
Int I, k, tmp;
For (I = 1; I <= n; I ++) rank [sa [I] = I;
K = 0;
For (I = 0; I <n; I ++)
{
Tmp = sa [rank [I]-1];
For (; r [I + k] = r [tmp + k]; k ++)
;
Height [rank [I] = k;
K? -- K: 0;
}
}
Int check (int n, int len, int tnum)
{
Int I, j, cnt = 0, tmp;
For (I = 0; I <tnum; I ++) flag [I] = 0;
Tmp = pos [sa [1];
Flag [tmp] = 1; rec [cnt ++] = tmp;
For (I = 2; I <= n; I ++)
{
Tmp = pos [sa [I];
If (height [I] <len)
{
For (j = 0; j <cnt; j ++)
Flag [rec [j] = 0;
Cnt = 0;
Rec [cnt ++] = tmp;
Flag [tmp] = 1;
}
Else
{
If (! Flag [tmp])
{
Rec [cnt ++] = tmp;
Flag [tmp] = 1;
}
If (cnt = tnum)
{
St = sa [I];
Ed = sa [I] + len;
Return true;
}
}
}
Return false;
}
Char s [M];
Char str [220];
Int main ()
{
Int I, j, n, tlen, len;
While (scanf ("% d", & n), n)
{
Tlen = 0;
For (I = 0; I <n; I ++)
{
Scanf ("% s", str );
Len = strlen (str );
For (j = 0; j <len; j ++)
{
R [tlen + j] = str [j]-'A' + 4100;
Pos [tlen + j] = I;
}
If (I <n-1)
R [tlen + len] = I + 1;
Else r [tlen + len] = 0;
Pos [tlen + len] = I;
Tlen + = len + 1;
}
For (I = 0; I <n; I ++) flag [I] = 0;
Da (tlen, 4500 );
Calh (tlen-1 );
Int le, ri, mid;
Le = 1; ri = len;
While (le <= ri)
{
Mid = (le + ri)> 1;
If (check (tlen-1, mid, n) le = mid + 1;
Else ri = mid-1;
}
If (ri = 0)
Puts ("identity lost ");
Else
{
For (I = st; I <ed; I ++)
Printf ("% c", r [I]-4100 + 'A ');
Puts ("");
}
}
}
Prepared by Wings_of_Liberty