题目大意: 求多个字符串的最长公共子串。
题解
将这些字符串拼在一起,中间用字符集以外的不同字符隔开,求出 h e i g h t height height 数组,那么答案就是要在 h e i g h t height height 数组里面找一段连续的 h e i g h t height height,其中包含以每个字符串中的字符为起点的后缀,然后这段 h e i g h t height height 中的最小值就是答案。
实现的话有两种方法,第一种是二分这个最小值,然后每次 O ( n ) O(n) O(n) 找是否存在连续的一段,满足所有 h e i g h t height height 都大于等于这个最小值且满足要求,第二种方法是用 t w o − p o i n t e r two-pointer two−pointer 维护一个单调队列,单调队列维护最小的 h e i g h t height height,每次当 l l l ~ r r r 中的元素满足要求时,用最小的 h e i g h t height height 更新一下答案。
由于 t w o − p o i n t e r two-pointer two−pointer 的时间复杂度为 O ( n ) O(n) O(n),相比二分更优秀,所以代码中用的是这种做法:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 2000010
int n,m,tot,id=0,belong[maxn];
char s[maxn],ss[maxn];
int fir[maxn],sec[maxn],c[maxn],sa[maxn],rk[maxn],height[maxn];
void get_sa()
{
m=200;
for(int i=1;i<=n;i++)c[i]=0;
for(int i=1;i<=n;i++)c[fir[i]=s[i]]++;
for(int i=2;i<=m;i++)c[i]+=c[i-1];
for(int i=n;i>=1;i--)sa[c[fir[i]]--]=i;
for(int k=1;k<n;k<<=1)
{
int tot=0;
for(int i=n-k+1;i<=n;i++)sec[++tot]=i;
for(int i=1;i<=n;i++)if(sa[i]>k)sec[++tot]=sa[i]-k;
for(int i=1;i<=m;i++)c[i]=0;
for(int i=1;i<=n;i++)c[fir[i]]++;
for(int i=2;i<=m;i++)c[i]+=c[i-1];
for(int i=n;i>=1;i--)sa[c[fir[sec[i]]]--]=sec[i],sec[i]=0;
for(int i=1;i<=n;i++)swap(fir[i],sec[i]);
fir[sa[1]]=tot=1;
for(int i=2;i<=n;i++)
if(sec[sa[i]]==sec[sa[i-1]]&&sec[sa[i]+k]==sec[sa[i-1]+k])fir[sa[i]]=tot;
else fir[sa[i]]=++tot;
if(tot==n)break;m=tot;
}
}
void get_height()
{
int k=0;
for(int i=1;i<=n;i++)rk[sa[i]]=i;
for(int i=1;i<=n;i++)
{
if(rk[i]==1){height[rk[i]]=0;continue;}
if(k)k--; int j=sa[rk[i]-1];
while(i+k<=n&&j+k<=n&&s[i+k]==s[j+k])k++;
height[rk[i]]=k;
}
}
int q[maxn],st=1,ed=0,v[maxn];
void add(int x)
{
if(!belong[sa[x]])return;
v[belong[sa[x]]]++;
if(v[belong[sa[x]]]==1)tot++;
}
void del(int x)
{
if(!belong[sa[x]])return;
v[belong[sa[x]]]--;
if(!v[belong[sa[x]]])tot--;
}
int work()
{
int l=1,ans=0;tot=0;
add(1);
for(int r=2;r<=n;r++)
{
while(st<=ed&&height[r]<=height[q[ed]])ed--;
q[++ed]=r; add(r);//加一个新的
if(tot==id)
{
while(tot==id&&l<r)del(l++); add(--l);
//把左边多余的去掉,显然不会使答案更小,但有可能使答案变大
while(st<=ed&&q[st]<=l)st++;//把队列中被去掉的踢出队列
ans=max(ans,height[q[st]]);//更新答案
}
}
return ans;
}
int main()
{
while(scanf("%s",ss+1)!=EOF)
{
m=strlen(ss+1); id++;
for(int i=1;i<=m;i++)s[++n]=ss[i],belong[n]=id;
s[++n]=id;
}
get_sa();get_height();
printf("%d",work());
}