3160 最长公共子串
时间限制: 2 空间限制: 128000 KB 题目等级 : 大师 Master
题目描述 Description
给出两个由小写字母组成的字符串,求它们的最长公共子串的长度。
输入描述 Input Description
读入两个字符串
输出描述 Output Description
输出最长公共子串的长度
样例输入 Sample Input
yeshowmuchiloveyoumydearmotherreallyicannotbelieveit
yeaphowmuchiloveyoumydearmother
样例输出 Sample Output
27
数据范围及提示 Data Size & Hint
单个字符串的长度不超过100000
题解
字符串hash
先预处理出前i个字符串的hash值,就像前缀积一样,以便O(1)查找字符串[l,r]的hash值,二分最长公共长度k,判断这个公共长度可不可以达到,判断时,将A串中长度为k的字符串提取出来,排序,之后每次在B串中拿出一个长度为k的串,依旧二分查找这个子串在A串中是否出现过。总复杂度O(n*log^2(n))
据说有什么大佬解法,用后缀数组也可以搞,目前不会
源代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;
typedef unsigned long long ULL;
int la,lb;
char a[100100],b[100100];
ULL na[100100],nb[100100];
ULL cmp[100100];
ULL pow(ULL x,int y){
ULL rtn=1;
while(y){
if(y&1)rtn*=x;
x*=x;y>>=1;
}
return rtn;
}
bool init(int l,int r,ULL x){
while(l<r){
int mid=l+r>>1;
if(x==cmp[mid])return true;
if(x>cmp[mid])l=mid+1;
else r=mid-1;
}
if(x==cmp[l])return true;
return false;
}
bool ok(int x){
memset(cmp,0,sizeof(cmp));
ULL k=pow(255,x);
for(int i=1;i+x-1<=la;i++)
cmp[i]=na[i+x-1]-k*na[i-1];
sort(cmp+1,cmp+la-x+2);
for(int i=1;i+x-1<=lb;i++){
ULL now=nb[i+x-1]-k*nb[i-1];
if(init(1,la-x+1,now))return true;
}
return false;
}
void pre(){
for(int i=1;i<=la;i++)
na[i]=na[i-1]*255+a[i-1];
for(int i=1;i<=lb;i++)
nb[i]=nb[i-1]*255+b[i-1];
}
int main(){
scanf("%s%s",a,b);
la=strlen(a),lb=strlen(b);
pre();
int l=0,r=max(la,lb);
while(l!=r){
int mid=(l+r>>1)+1;
if(ok(mid))l=mid;
else r=mid-1;
}
printf("%d",l);
}