【BZOJ 2946】 2946: [Poi2000]公共串 (SAM)

时间:2023-11-11 19:46:56

2946: [Poi2000]公共串

Time Limit: 3 Sec  Memory Limit: 128 MB
Submit: 1063  Solved: 469

Description

       给出几个由小写字母构成的单词,求它们最长的公共子串的长度。
任务:
l        读入单词
l        计算最长公共子串的长度
l        输出结果

Input

文件的第一行是整数 n,1<=n<=5,表示单词的数量。接下来n行每行一个单词,只由小写字母组成,单词的长度至少为1,最大为2000。

Output

仅一行,一个整数,最长公共子串的长度。

Sample Input

3
abcb
bca
acbc

Sample Output

HINT

Source

【分析】

  重新学一次SAM,从刷水题开始。

  同spoj1812。用第一个串建sam,然后用其他的串跑,ans存在那个点那里,做完一个串的时候还要根据parent边的拓扑序更新该点ans,最后取min即可。

  当然后缀数组也是可以的。

 #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define Maxn 2010 int mymax(int x,int y) {return x>y?x:y;}
int mymin(int x,int y) {return x<y?x:y;} struct node
{
int pre,son[],step;
// node() {pre=step=0;memset(son,0,sizeof(son));}
}t[Maxn*];
int ans[Maxn*],ad[Maxn*]; struct sam
{
int last,tot;
/*void upd(int x)
{
memset(t[x].son,0,sizeof(t[x].son));
}*/
void extend(int k)
{
int np=++tot,p=last;
t[np].step=t[last].step+;
while(p&&!t[p].son[k])
{
t[p].son[k]=np;
p=t[p].pre;
}
if(!p) t[np].pre=;
else
{
int q=t[p].son[k];
if(t[q].step==t[p].step+) t[np].pre=q;
else
{
int nq=++tot;//upd(tot);
t[nq].step=t[p].step+;
memcpy(t[nq].son,t[q].son,sizeof(t[nq].son));
t[nq].pre=t[q].pre;
t[q].pre=t[np].pre=nq;
while(p&&t[p].son[k]==q)
{
t[p].son[k]=nq;
p=t[p].pre;
}
}
}
last=np;
} }sam; char s[],ss[Maxn]; int main()
{
int n;scanf("%d",&n);
scanf("%s",s);
sam.last=sam.tot=;
int l=strlen(s);
for(int i=;i<l;i++) sam.extend(s[i]-'a'+);
memset(ans,,sizeof(ans));
for(int i=;i<=n;i++)
{
scanf("%s",s);
l=strlen(s);
int nw=,sp=;
for(int j=;j<=sam.tot;j++) ad[j]=;
for(int j=;j<l;j++)
{
int ind=s[j]-'a'+;
while(nw&&!t[nw].son[ind]) nw=t[nw].pre,sp=t[nw].step;
if(t[nw].son[ind]) sp++,nw=t[nw].son[ind];
else nw=,sp=;
ad[nw]=mymax(ad[nw],sp);
}
for(int i=sam.tot;i>=;i--) ad[t[i].pre]=mymax(ad[t[i].pre],mymin(ad[i],t[t[i].pre].step));
for(int i=sam.tot;i>=;i--) ans[i]=mymin(ans[i],ad[i]);
}
int mx=;
for(int i=;i<=sam.tot;i++) if(ans[i]<=sam.tot) mx=mymax(mx,ans[i]);
printf("%d\n",mx);
return ;
}

2017-04-17 10:21:42