把两个字符串连在一起,中间用个字符隔开。排名差1,并且首字母分别在两个串的后缀,所对应的height的最小值即为所求
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define maxn 200010
int n,m;
int r[maxn];
int wa[maxn], wb[maxn], wv[maxn], ws[maxn];
int sa[maxn], rank[maxn], height[maxn];
int cmp(int *r, int a, int b, int l){
return r[a]==r[b] && r[a+l]==r[b+l];
}
void sortSuffix(int *r,int *sa,int n,int m){
int i, j, p, *x = wa, *y = wb, *t;
for(i = 0; i < m; i++) ws[i] = 0;
for(i = 0; i < n; i++) ws[x[i] = r[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 *= 2, 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];
t = x, x = y, y = t, p = 1, x[sa[0]] = 0;
for(i = 1;i < n; i++)
x[sa[i]] = cmp(y,sa[i-1],sa[i],j) ? p-1:p++;
}
}
void calHeight(int *r, int *sa, int n){
int i, j, k = 0;
for(i = 1; i <= n; i++) rank[sa[i]] = i;
for(i = 0; i < n; i++){
for(k? k--:0, j=sa[rank[i]-1]; r[i+k]==r[j+k]; k++);
height[rank[i]] = k;
}
}
int main()
{
char a[100010],b[100010];
while(scanf("%s%s",&a,&b)!=EOF)
{
int la=strlen(a),lb=strlen(b);
n=la+lb+1;
for(int i=0;i<la;i++)r[i]=a[i]-'a'+1;
r[la]=30;
for(int i=la+1;i<=la+lb;i++)r[i]=b[i-la-1]-'a'+1;
r[n]=0;
sortSuffix(r,sa,n+1,40);
calHeight(r,sa,n);
int ans=0;
for(int i=2;i<la+lb+1;i++)
{
if(ans<height[i])
if((sa[i]<la&&sa[i-1]>la+1)||(sa[i-1]<la&&sa[i]>la+1))
ans=height[i];
}
printf("%d\n",ans);
}
return 0;
}