• 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);
    }
    
  • 相关阅读:
    20155327 2017-2018-2 《Java程序设计》第9周学习总结
    20155327《Java程序设计》第八周学习总结
    实验二 Java面向对象程序设计
    20155327 李百乾 Exp4 恶意代码分析
    20155327结对编程练习
    20155327第七周学习总结
    2017-2018-1 20155310 20155337 实验五 通讯协议设计
    # 2017-2018-1 20155337《信息安全系统设计基础》第十三周学习总结
    # 20155337 2017-2018 1 课上测试、课下作业、实验
    # 课下测试ch02
  • 原文地址:https://www.cnblogs.com/zhenglier/p/10098060.html
Copyright © 2020-2023  润新知