后缀数组
#include <iostream>#include <cstdio>#include <cstring>usingnamespacestd;
constint maxn=200000+100;
int wa[maxn], wb[maxn], wv[maxn], Ws[maxn];
int Rank[maxn], height[maxn];
int sa[maxn], r[maxn];
char str[maxn];
int cmp(int* r, int a, int b, int l)
{
return r[a] == r[b] && r[a + l] == r[b + l];
}
//将原串利用ascii码复制到r数组中,r[len]=0;//m是原串中ascii码最大值加一,合理设值,会影响通排序的基数//复杂度 nlogn//n+1//sa 是从1...n 然后sa[]是字符串下表 从0~~n//rank 是0...n,val 从1~~ rank[0]=2 代表suffix(0)在所有后缀中排第二名void da(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 (p = 1, j = 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];
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++;
}
}
//n//复杂度:nlogn//height 数组下表是1...lenvoid 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; height[Rank[i++]] = k)
for (k ? k-- : 0, j = sa[Rank[i] - 1]; r[i + k] == r[j + k]; k++)
;
}
int main()
{
//freopen("in.txt", "r", stdin);//cout<<(int)'z'<<endl;while(scanf("%s",str)!=EOF) {
int len2=(int)(strlen(str));
str[len2]='#';
scanf("%s",str+len2+1);
int len=(int)strlen(str);
for(int i=0;i<len;i++) r[i]=str[i];
r[len]=0;
da(r, sa, len+1, 180);
calheight(r, sa, len);
int ans=0;
for(int i=2;i<len;i++) {
if(ans<height[i])
if((sa[i]<len2&&sa[i-1]>len2)||(sa[i]>len2&&sa[i-1]<len2))
ans=height[i];
}
printf("%d\n",ans);
}
return0;
}