求两个串的公共最长前缀
#include <cstdio>
#include <cstring>
#define maxn 200010
char s[maxn];
int n,m,sa[maxn],rank[maxn],height[maxn];
int wa[maxn],wb[maxn],ws[maxn],wv[maxn];
inline bool cmp(int *r,int a,int b,int l)
{
return (r[a] == r[b]) && (r[a+l] == r[b+l]);
}
inline void da(int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
memset(ws,0,sizeof(ws));
for (i=0;i<n;++i) ws[x[i]=s[i]]++;
for (i=1;i<m;++i) ws[i]+=ws[i-1];
for (i=n-1;i>=0;--i) sa[--ws[x[i]]]=i;
for (j=1,p=1;p<n;j<<=1,m=p)
{
for (p=0,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<n;++i) wv[i]=x[y[i]];
for (i=0;i<m;++i) ws[i]=0;
for (i=0;i<n;++i) ws[wv[i]]++;
for (i=1;i<m;++i) ws[i]+=ws[i-1];
for (i=n-1;i>=0;--i) sa[--ws[wv[i]]]=y[i];
for (t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i<n;++i)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
}
}
inline void calcheight()
{
int i,j,k=0;
for (i=1;i<=n;++i) rank[sa[i]]=i;
for (i=0;i<n;height[rank[i++]]=k)
for (k?k--:0,j=sa[rank[i]-1];s[i+k]==s[j+k];k++);
}
int main()
{
scanf("%d",&m);
scanf("%s%s",s,s+m+1);
s[m]=1;
n=m+m+1;
da(n+1,255);
calcheight();
int ans=0,tmp;
for(int i=2;i<=n;++i)
if(ans<height[i])
if((sa[i-1]<m&&sa[i]>m)||(sa[i-1]>m&&sa[i]<m))
ans=height[i],tmp=sa[i];
s[tmp+ans]='\0';
printf("%s\n",s+tmp);
return 0;
}