Corporate Identity:
给定n(n <= 4000)个长度不超过200的字符串,求最长公共子串
样例输入
3
aabbaabb
abbababb
bbbbbabb
2
xyz
abc
0
样例输出
abb
IDENTITY LOST
写得不是很好,卡着时间过了
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <deque>
using namespace std;
const int MAXN = 810000;
int all[MAXN];
int sa[MAXN]; //sa[i]表示位次为i的后缀的位置
int height[MAXN]; //height[i]表示位次为i的后缀与位次为i-1的后缀的最长公共前缀
int ra[MAXN];
int wa[MAXN], wb[MAXN], wv[MAXN], Ws[MAXN];
int t;
struct seg
{
int leftpoint;
int rightpoint;
};
seg s[5000];
void BuildSA(int* s, int sa[], int n, int m)
{
int i, j, p, *pm = wa, *k2sa = wb, *t;
for (i = 0; i < m; i++)
Ws[i] = 0;
for (i = 0; i < n; i++)
Ws[pm[i] = s[i]]++;
for (i = 1; i < m; i++)
Ws[i] += Ws[i - 1];
for (i = n - 1; i >= 0; i--)
sa[--Ws[pm[i]]] = i;
for (j = p = 1; p < n; j <<= 1, m = p)
{
for (p = 0, i = n - j; i < n; i++)
k2sa[p++] = i;
for (i = 0; i < n; i++)
if (sa[i] >= j)
k2sa[p++] = sa[i] - j;
for (i = 0; i < m; i++)
Ws[i] = 0;
for (i = 0; i < n; i++)
Ws[wv[i] = pm[k2sa[i]]]++;
for (i = 1; i < m; i++)
Ws[i] += Ws[i - 1];
for (i = n - 1; i >= 0; i--)
sa[--Ws[wv[i]]] = k2sa[i];
for (t = pm, pm = k2sa, k2sa = t, pm[sa[0]] = 0, p = i = 1; i < n; i++)
{
int a = sa[i - 1], b = sa[i];
if (k2sa[a] == k2sa[b] && k2sa[a + j] == k2sa[b + j])
pm[sa[i]] = p - 1;
else
pm[sa[i]] = p++;
}
}
return;
}
void BuildHeight(int* str, int n, int* sa, int* Rank)
{
int i, j, k;
for (int i = 0; i < n; ++i)
Rank[sa[i]] = i;
for (i = k = 0; i < n; height[Rank[i++]] = k)
for (k ? k-- : 0, j = sa[Rank[i] - 1]; str[i + k] == str[j + k]; k++);
}
int visited[4010];
int ind;
bool cal(int l, int m)
{
memset(visited, 0, sizeof(visited));
int sum = 0;
for (int i = 0; i < l; i++)
{
if (height[i] >= m)
{
if (sum == 0)
{
for (int j = 0; j < t; j++)
{
if (sa[i - 1] >= s[j].leftpoint&&sa[i - 1] <= s[j].rightpoint)
{
if (visited[j] == 0)
{
visited[j] = 1;
sum++;
}
break;
}
}
}
sum++;
ind = sa[i];
int flag2 = 0;
for (int j = 0; j < t; j++)
{
if (sa[i] >= s[j].leftpoint&&sa[i] <= s[j].rightpoint)
{
if (visited[j] == 0)
{
visited[j] = 1;
sum++;
}
break;
}
}
}
else
{
sum = 0;
memset(visited, 0, sizeof(visited));
continue;
}
if (sum >= t)
{
int flag = 0;
for (int j = 0; j < t; j++)
{
if (visited[j] == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
return 1;
}
}
return 0;
}
int main()
{
cin >> t;
while (t != 0)
{
int l = 0;
int numbers = 0;
string c;
for (int i = 1; i <= t; i++)
{
cin >> c;
int ls = c.size();
s[numbers].leftpoint = l;
for (int j = 0; j < ls; j++)
{
all[l++] = c[j] - 'a' + 1;
}
s[numbers++].rightpoint = l - 1;
all[l++] = 100 + i;
}
all[l++] = 0;
BuildSA(all, sa, l, 5000);
BuildHeight(all, l, sa, ra);
int left = 0;
int right = 4000;
int mid;
while (left < right)
{
mid = (left + right) / 2;
if (mid == left)
mid++;
if (cal(l, mid))
left = mid;
else
right = mid - 1;
}
cal(l, left);
if (left == 0)
cout << "IDENTITY LOST" << endl;
else
{
for (int i = 0; i < left; i++)
{
char q = 'a' - 1 + all[ind + i];;
cout << q;
}
cout << endl;
}
cin >> t;
}
return 0;
}```