[POI2000 bzoj2946]公共串

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

分析:
1.第一个串放进去建后缀自动机
2.以后的每个串依次匹配,看到达每个状态的最短长度
3.取所有状态的最大值

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iostream>
using namespace std;
const int maxn=4010;
int n;
char str[maxn];
int last;
int e;
int len[maxn];
void read(int& x){
    x=0;
    char c=getchar();
    while(c<'0' || c>'9') c=getchar();
    while(c>='0' && c<='9'){
        x=x*10+c-'0';
        c=getchar();
    }
}
struct Suffix_Automaton{
    int ch[maxn][26],pre[maxn],Max[maxn];
    int cnt[maxn],rk[maxn];
    int ans[maxn];
    Suffix_Automaton(){
        last=++e;
    }
    void extand(int c){
        int p=last,np=++e;Max[np]=Max[p]+1;last=np;
        for(;p && !ch[p][c];p=pre[p]) ch[p][c]=np;
        if(!p) pre[np]=1;
        else{
            int q=ch[p][c];
            if(Max[q]!=Max[p]+1){
                int nq=++e;Max[nq]=Max[p]+1;
                for(int i=0;i<26;i++) ch[nq][i]=ch[q][i];
                pre[nq]=pre[q];
                pre[q]=pre[np]=nq;
                for(;ch[p][c]==q;p=pre[p]) ch[p][c]=nq;
            }else pre[np]=q;
        }
    }
    void Pre(){
        for(int i=1;i<=e;i++) ans[i]=Max[i];
        for(int i=1;i<=e;i++) cnt[Max[i]]++;
        for(int i=1;i<=e;i++) cnt[i]+=cnt[i-1];
        for(int i=e;i>=1;i--) rk[cnt[Max[i]]--]=i;
    }
    void solve(){
        scanf("%s",str+1);
        memset(len,0,sizeof(len));
        int p=1,tmp=0;
        for(int i=1;i<=strlen(str+1);i++){
            int c=str[i]-'a';
            for(;!ch[p][c] && p;p=pre[p]);
            if(!p) p=1,tmp=0;
            else tmp=min(tmp,Max[p])+1,p=ch[p][c];
            len[p]=max(len[p],tmp);
        }
        for(int i=e;i>=1;i--) len[pre[rk[i]]]=max(len[pre[rk[i]]],len[rk[i]]);
        for(int i=1;i<=e;i++) ans[i]=min(ans[i],len[i]);
    }
}sam;
int ans;
int main(){
    read(n);
    scanf("%s",str+1);
    for(int i=1;i<=strlen(str+1);i++) sam.extand(str[i]-'a');
    sam.Pre();
    for(int i=1;i<n;i++) sam.solve();
    for(int i=1;i<=e;i++) ans=max(ans,sam.ans[i]);
    printf("%d",ans);
    return 0;
}

^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值