LCS - Longest Common Substring(spoj1811) (sam(后缀自动机)+LCS)

A string is finite sequence of characters over a non-empty finite set \(\sum\).

In this problem, \(\sum\) 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

题意:

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

题解:

把第一个串建一个后缀自动机,然后把另一个串放在上面从根(1号节点)开始跑,如果失配,就往\(parent\)上跳,并把当前长度变为\(parent\)\(len\);若匹配,把当前长度加一,并实时更新答案。

#include<bits/stdc++.h>
using namespace std;
const int N=2000010;
char s[N];
int a[N],c[N];
struct SAM{
    int last,cnt;
    int size[N],ch[N][26],fa[N<<1],l[N<<1];
    void ins(int c){
        int p=last,np=++cnt;last=np;l[np]=l[p]+1;
        for(;p&&!ch[p][c];p=fa[p])ch[p][c]=np;
        if(!p)fa[np]=1;
        else{
            int q=ch[p][c];
            if(l[p]+1==l[q])fa[np]=q;
            else{
                int nq=++cnt;l[nq]=l[p]+1;
                memcpy(ch[nq],ch[q],sizeof ch[q]);
                fa[nq]=fa[q];fa[q]=fa[np]=nq;
                for(;ch[p][c]==q;p=fa[p])ch[p][c]=nq;
            }
        }
        size[np]=1;
    }
    void build(char s[]){
        int len=strlen(s+1);
        last=cnt=1;
        for(int i=1;i<=len;++i)ins(s[i]-'a');
    }
    void work(char s[]){
        int len=strlen(s+1);
        int p=1,left=0,as=0,ans=0;
        while(left<=len){
            left++;
            while(p&&(!ch[p][s[left]-'a']))p=fa[p],as=l[p];
            if(!p)p=1,as=0;
            else{
                as++;
                ans=max(ans,as);
                p=ch[p][s[left]-'a'];
            }
        }
        cout<<ans<<endl;
    }
}sam;
int main(){
    cin>>s+1;
    sam.build(s);
    cin>>s+1;
    sam.work(s);
}
posted @ 2018-12-10 18:26  整理者  阅读(199)  评论(0编辑  收藏  举报