[bzoj2946]公共串

题目大意

求n个字符串的最长公共子串

SAM

对第一个字符串建SAM
每个节点为护f[i]表示所有串与该状态匹配的最长长度。
对于每一个字符串,都在SAM上跑,并每次都计算g[i]表示字符串与状态i匹配的最大长度。
做完后用g和f取min更新f。
每次跑完后,要逆推计算g。对于i,若g[i]>0,则g[pre[i]]=step[pre[i]]。因为i成功被匹配了,匹配长度>step[pre[i]],pre[i]也被匹配了,一定是step[pre[i]]被匹配掉了。
最后在f中取最大值。

#include<cstdio>
#include<algorithm>
#include<cstring>
#define fo(i,a,b) for(i=a;i<=b;i++)
#define fd(i,a,b) for(i=a;i>=b;i--)
using namespace std;
const int maxn=2000+10;
int pre[maxn*2],step[maxn*2],g[maxn*2][26],cnt[maxn*2],a[maxn*2];
int f[maxn*2],b[maxn*2];
char s[maxn];
int i,j,k,l,t,n,m,p,x,tot,last,len,ans;
void add(int x){
    int np=++tot,p=last;
    step[np]=step[p]+1;
    while (p&&g[p][x]==0){
        g[p][x]=np;
        p=pre[p];
    }
    if (!p) pre[np]=1;
    else{
        int q=g[p][x];
        if (step[q]==step[p]+1) pre[np]=q;
        else{
            int nq=++tot,i;
            fo(i,0,25) g[nq][i]=g[q][i];
            step[nq]=step[p]+1;
            pre[nq]=pre[q];
            pre[q]=nq;
            pre[np]=nq;
            while (p&&g[p][x]==q){
                g[p][x]=nq;
                p=pre[p];
            }
        }
    }
    last=np;
}
int main(){
    scanf("%d",&n);
    scanf("%s",s+1);
    last=tot=1;
    len=strlen(s+1);
    fo(i,1,len) add(s[i]-'a');
    fo(i,1,tot) f[i]=step[i];
    fo(i,1,tot) cnt[step[i]]++;
    fo(i,1,len) cnt[i]+=cnt[i-1];
    fo(i,1,tot) a[cnt[step[i]]--]=i;
    n--;
    while (n--){
        fo(i,1,tot) b[i]=0;
        scanf("%s",s+1);
        len=strlen(s+1);
        p=1;t=0;
        fo(i,1,len){
            x=s[i]-'a';
            while (p!=1&&!g[p][x]) p=pre[p];
            if (!g[p][x]) t=0;else t=min(t,step[p])+1;
            if (g[p][x]) p=g[p][x];
            b[p]=max(b[p],t);
        }
        fd(i,tot,1) 
            if (b[a[i]]) b[pre[a[i]]]=step[pre[a[i]]];
        fo(i,1,tot) f[i]=min(f[i],b[i]);
    }
    ans=0;
    fo(i,1,tot)
        ans=max(ans,f[i]);
    printf("%d\n",ans);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值