[POJ2774]Long Long Message
一句话题意
给两个串,求最长公共子串。
sol
把两个串接在一起求后缀数组。其实中间最好用一个没有出现过的字符连接起来。
判断如果\(SA[i]\)和\(SA[i-1]\)不属于同一个串的话就可以拿\(Height[i]\)更新答案
code
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define ll long long
int gi()
{
int x=0,w=1;char ch=getchar();
while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if (ch=='-') w=0,ch=getchar();
while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return w?x:-x;
}
const int N = 2e5+5;
char s1[N],s2[N];
int n,n1,n2,a[N],t[N],x[N],y[N],SA[N],Rank[N],Height[N],ans;
bool cmp(int i,int j,int k){return y[i]==y[j]&&y[i+k]==y[j+k];}
void getSA()
{
int m=30;
for (int i=1;i<=n;++i) ++t[x[i]=a[i]];
for (int i=1;i<=m;++i) t[i]+=t[i-1];
for (int i=n;i>=1;--i) SA[t[x[i]]--]=i;
for (int k=1;k<=n;k<<=1)
{
int p=0;
for (int i=0;i<=m;++i) y[i]=0;
for (int i=n-k+1;i<=n;++i) y[++p]=i;
for (int i=1;i<=n;++i) if (SA[i]>k) y[++p]=SA[i]-k;
for (int i=0;i<=m;++i) t[i]=0;
for (int i=1;i<=n;++i) ++t[x[y[i]]];
for (int i=1;i<=m;++i) t[i]+=t[i-1];
for (int i=n;i>=1;--i) SA[t[x[y[i]]]--]=y[i];
swap(x,y);
x[SA[1]]=p=1;
for (int i=2;i<=n;++i) x[SA[i]]=cmp(SA[i],SA[i-1],k)?p:++p;
if (p>=n) break;
m=p;
}
for (int i=1;i<=n;++i) Rank[SA[i]]=i;
for (int i=1,j=0;i<=n;++i)
{
if (j) --j;
while (a[i+j]==a[SA[Rank[i]-1]+j]) ++j;
Height[Rank[i]]=j;
}
}
bool diff(int i,int j){return (i<=n1&&j>n1)||(i>n1&&j<=n1);}
int main()
{
scanf("%s",s1+1);n1=strlen(s1+1);
scanf("%s",s2+1);n2=strlen(s2+1);
n=n1+n2;
for (int i=1;i<=n1;++i) a[i]=s1[i]-96;
for (int i=1;i<=n2;++i) a[n1+i]=s2[i]-96;
getSA();
for (int i=1;i<=n;++i)
if (diff(SA[i],SA[i-1]))
ans=max(ans,Height[i]);
printf("%d\n",ans);
return 0;
}