spoj 1811 LCS 后缀自动机

本文介绍使用后缀自动机(SAM)解决两个字符串的最长公共子串问题,包括SAM的基本概念、关键性质及实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A string is finite sequence of characters over a non-empty finite set Σ.
In this problem, Σ is the set of lowercase letters.
Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.
Now your task is simple, for two given strings, find the length of the longest common substring of them.
Here common substring means a substring of two or more strings.
Input
The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.
Output
The length of the longest common substring. If such string doesn’t exist, print “0” instead.
Example
Input:
alsdfkjfjkdsal
fdjskalajfkdsla

Output:
3
Notice: new testcases added


传送门
题意:给出两个串,求它们的最长公共子串。
本来其实是想着后缀数组做的。。
然后就看见评论里说”suffix array will not work”
吓尿了……百度后才发现这题O(NlogN)要被卡!噗。。
好吧只好用自动机做了。
我对后缀自动机感觉理解欠一点,
这题也想了好久。。
主要就是:DAG,
还有parent树的种种性质(一个点的pre(或者说parent)结点,
右端点集合>这个点的右端点集合,所以长度肯定更短)
说不大清楚,建议自己去学学(=v=)
那么如何求LCS呢?首先在自动机上,有当前ch的边,
就往那边走,
不然肯定要退回到某一个部分,具体就是一个点p,
这个部分,满足后缀与当前匹配到的一致,
且有ch的边(如果没有这种点的话直接回到root去重新开始就好了)
那么长度更新成step[p]+1,并且走它的ch儿子。
中途不停更新ans的最大值即可。

这个比较好理解。因为后缀部分一定匹配了,
那么最长公共子串一定建立在某部分匹配的基础上,
parent树就是这么nb……

注意啦sam的数组开2倍(最多2n-1个点)

#include<bits/stdc++.h>
using namespace std;
const int 
    N=250005;
int tot;
struct SAM{
    int last,step[N<<1],pre[N<<1];
    int son[N<<1][26];
    SAM(){
        last=1;
        memset(son,0,sizeof(son));
        memset(pre,0,sizeof(pre));
        memset(step,0,sizeof(step));
    }
    void insert(int c){
        int p=last,np=++tot;
        step[np]=step[p]+1;
        for (;p && !son[p][c];p=pre[p]) son[p][c]=np;
        if (!p) pre[np]=1;
         else{
            int q=son[p][c];
            if (step[p]+1!=step[q]){
                int nq=++tot;
                step[nq]=step[p]+1;
                memcpy(son[nq],son[q],sizeof(son[nq]));
                pre[nq]=pre[q];
                pre[q]=pre[np]=nq;
                for (;son[p][c]==q;p=pre[p]) son[p][c]=nq;
            } else pre[np]=q;
        }
        last=np;
    }
}sam;
int main(){
    char s[N];
    scanf("%s",s+1);
    int n=strlen(s+1);
    tot=1;
    for (int i=1;i<=n;i++) sam.insert(s[i]-'a');
    scanf("%s",s+1);
    n=strlen(s+1);
    int ans=0,len=0,p=1;
    for (int i=1;i<=n;i++){
        if (sam.son[p][s[i]-'a'])
            len++,p=sam.son[p][s[i]-'a'];
         else{
            for (;p && !sam.son[p][s[i]-'a'];p=sam.pre[p]);
            if (!p) len=0,p=1;
                else len=sam.step[p]+1,p=sam.son[p][s[i]-'a'];
         }
        ans=max(ans,len);
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值