POJ 2774 求两个串的最长公共前缀 | 后缀数组
#include<cstdio> #include<algorithm> #include<cstring> #define N 200005 using namespace std; int buf1[N],buf2[N],sa[N],rnk[N],buc[N],n,height[N],ans,belong[N]; char s[N]; void suffix_sort() { int *x=buf1,*y=buf2,m=1000; for (int i=0;i<m;i++) buc[i]=0; for (int i=1;i<=n;i++) buc[x[i]=s[i]]++; for (int i=1;i<=m;i++) buc[i]+=buc[i-1]; for (int i=n;i;i--) sa[buc[x[i]]--]=i; for (int k=1;k<=n;k<<=1) { int p=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++) buc[i]=0; for (int i=1;i<=n;i++) buc[x[y[i]]]++; for (int i=1;i<=m;i++) buc[i]+=buc[i-1]; for (int i=n;i;i--) sa[buc[x[y[i]]]--]=y[i]; swap(x,y),x[sa[1]]=p=1; for (int i=2;i<=n;i++) if (y[sa[i-1]]==y[sa[i]] && y[sa[i-1]+k]== y[sa[i]+k]) x[sa[i]]=p; else x[sa[i]]=++p; if ((m=p)>=n) break; } for (int i=1;i<=n;i++) rnk[sa[i]]=i; for (int i=1,j,k=0;i<=n;i++) { if (rnk[i]==1) continue; if (k) k--; j=sa[rnk[i]-1]; while (s[i+k]==s[j+k] && i+k<=n && j+k<=n) k++; height[rnk[i]]=k; } } int main() { scanf("%s",s+1); n=strlen(s+1); for (int i=1;i<=n;i++) belong[i]=2; s[n+1]='#'; scanf("%s",s+n+2); n=strlen(s+1); for (int i=1;i<=n;i++) if (--belong[i]==-1) belong[i]=2; suffix_sort(); for (int i=2;i<=n;i++) if (belong[sa[i]]!=belong[sa[i-1]]) ans=max(ans,height[i]); printf("%d\n",ans); return 0; }