Description
给出几个由小写字母构成的单词,求它们最长的公共子串的长度。
任务:
读入单词
计算最长公共子串的长度
输出结果
1<=n<=5
单词只由小写字母组成,长度至少为1,最大为2000。
Solution
我好弱啊,写完搜题解才发现可以巧妙地hash+二分
回忆一下两个串的时候把第一个建sam第二个扔上去跑,记录每一个节点向前能取到的最长长度,取max就是答案了(根据sam的定义)
那么多个串就同理,把第一个建sam剩下的分别扔上去跑。用tmp[j][i]记录当前串节点i能向前拓展最长长度,f[j][i]记录前j个串节点i向前拓展最长长度,显然可以用tmp更新f然后出答案
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define fill(x,t) memset(x,t,sizeof(x))
#define copy(x,t) memcpy(x,t,sizeof(x))
const int N=200005;
int rec[N][26],fa[N],len[N];
int tmp[N],f[N];
int last,cnt;
bool vis[N];
char str[6][N];
void extend(char ch) {
int p,q,np,nq;
p=last; last=np=++cnt;
while (p&&!rec[p][ch]) {
rec[p][ch]=np;
p=fa[p];
}
if (!p) fa[np]=1;
else {
q=rec[p][ch];
if (len[p]+1==len[q]) fa[np]=q;
else {
int nq=++cnt; len[nq]=len[p]+1;
copy(rec[nq],rec[q]);
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
while (p&&rec[p][ch]==q) {
rec[p][ch]=nq;
p=fa[p];
}
}
}
}
void solve(char *str) {
fill(tmp,0);
int now=1,l=0;
rep(i,0,strlen(str)-1) {
while (now&&!rec[now][str[i]-'a']) {
now=fa[now];
l=len[now];
vis[now]=1;
tmp[now]=std:: max(tmp[now],l);
}
if (!now) {
now=1;
l=0;
}
now=rec[now][str[i]-'a'];
l++;
vis[now]=1;
tmp[now]=std:: max(tmp[now],l);
}
rep(i,1,cnt) f[i]=std:: min(f[i],tmp[i]);
}
int main(void) {
int n; scanf("%d",&n);
rep(i,1,n) scanf("%s",str[i]);
cnt=last=1;
rep(i,0,strlen(str[1])-1) extend(str[1][i]-'a');
fill(f,31);
rep(i,2,n) solve(str[i]);
int ans=0;
rep(i,1,cnt) ans=std:: max(ans,f[i]);
printf("%d\n", ans);
return 0;
}