题意
给你串A,B求出AB中的最长公共子串
思路
将AB拼接中间加一个没有出现过的数(ascii最大值为127可以取200)然后求一边LCP再判断是不是在两个串中
复杂度为O(A+B)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<queue>
#include<vector>
#include<time.h>
#include<cmath>
using namespace std;
#define INF (1<<30)
typedef long long int LL;
const int MAXN = 100000 + 5;
/*
*suffix array
*倍增算法 O(n*logn)
*待排序数组长度为n,放在0~n-1中,在最后面补一个0
*build_sa( ,n+1, );//注意是n+1;
*getHeight(,n);
*例如:
*n = 8;
*num[] = { 1, 1, 2, 1, 1, 1, 1, 2, $ };注意num最后一位为0,其他大于0
*rank[] = { 4, 6, 8, 1, 2, 3, 5, 7, 0 };rank[0~n-1]为有效值,rank[n]必定为0无效值
*sa[] = { 8, 3, 4, 5, 0, 6, 1, 7, 2 };sa[1~n]为有效值,sa[0]必定为n是无效值
*height[]= { 0, 0, 3, 2, 3, 1, 2, 0, 1 };height[2~n]为有效值
*
*/
int wa[2*MAXN], wb[2*MAXN], wv[2*MAXN], WS[2*MAXN];
int cmp(int *r, int a, int b, int l){
return r[a] == r[b] && r[a + l] == r[b + l];
}
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 (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];
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++;
}
return;
}
int Rank[2*MAXN], height[2*MAXN],sa[2*MAXN];
//定义 height[i]=suffix(sa[i-1])和 suffix(sa[i])的最长公共前缀 [2,len]
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; height[Rank[i++]] = k)
for (k ? k-- : 0, j = sa[Rank[i] - 1]; r[i + k] == r[j + k]; k++);
return;
}
char str1[MAXN],str2[MAXN];
int r[2*MAXN];
int main()
{
while(~scanf("%s%s",str1,str2))
{
int len1=strlen(str1);
int len2=strlen(str2);
int count=0;
for(int i=0;i<len1;i++)
r[count++]=str1[i];
r[count++]=100;
for(int i=0;i<len2;i++)
r[count++]=str2[i];
r[count]=0;
da(r,sa,count+1,200);
calheight(r,sa,count);
int ans=0;
for(int i=2;i<=count;i++)
{
if(height[i]>ans)
{
if(sa[i]<len1&&sa[i-1]>=len1)
ans=height[i];
if(sa[i]>=len1&&sa[i-1]<len1)
ans=height[i];
}
}
cout<<ans<<endl;
}
}