• [SP1811] LCS


    Description

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

    Solution

    对 A 串建立 SAM,将 B 串扔到上面跑

    维护 tmp 表示当前已经匹配的长度,p 为当前自动机的状态(所在节点)

    如果能匹配就走 trans 边,否则沿着后缀链接跳,即令 p=link[p],此后令 tmp=maxlen[p]

    在所有出现过的 tmp 中取最大值作为 ans

    #include <bits/stdc++.h>
    using namespace std;
    const int Maxn = 2000005;
    struct Suffix_Automata {
        int maxlen[Maxn], trans[Maxn][26], link[Maxn], Size, Last;
        int t[Maxn], a[Maxn], cnt[Maxn], f[Maxn];
        Suffix_Automata() { Size = Last = 1; }
        inline void Extend(int id) {
            int cur = (++ Size), p;
            maxlen[cur] = maxlen[Last] + 1;
            cnt[cur] = 1;
            for (p = Last; p && !trans[p][id]; p = link[p]) trans[p][id] = cur;
            if (!p) link[cur] = 1;
            else {
                int q = trans[p][id];
                if (maxlen[q] == maxlen[p] + 1) link[cur] = q;
                else {
                    int clone = (++ Size);
                    maxlen[clone] = maxlen[p] + 1;
                    for(int i=0;i<26;i++) trans[clone][i] = trans[q][i];
                    link[clone] = link[q];
                    for (; p && trans[p][id] == q; p = link[p]) trans[p][id] = clone;
                    link[cur] = link[q] = clone;
                }
            }
            Last = cur;
        }
        int solve(string str) {
            int p=1, tmp=0, ans=0;
            for(int i=0;i<str.length();i++) {
                while(p>1 && trans[p][str[i]-'a']==0) p=link[p], tmp=maxlen[p];
                if(trans[p][str[i]-'a']) ++tmp, p=trans[p][str[i]-'a'];
                ans=max(ans,tmp);
            }
            return ans;
        }
    } sam;
    
    int main() {
        ios::sync_with_stdio(false);
        string str;
        cin>>str;
        int t,k;
        for(int i=0;i<str.length();i++)
            sam.Extend(str[i]-'a');
        string s;
        cin>>s;
        cout<<sam.solve(s);
    }
    
    
    
  • 相关阅读:
    docker 相关
    mongo 连接方式
    Redis 面试题
    Ubuntu如何挂载U盘
    python try异常处理之traceback准确定位哪一行出问题
    Opencv 基础用法
    CentOS 7 安装MongoDB 4.0(yum方式) 简单方便
    linux中pthread_join()与pthread_detach()详解
    C语言线程池 第三方库
    XML文件删除掉注释
  • 原文地址:https://www.cnblogs.com/mollnn/p/13174124.html
Copyright © 2020-2023  润新知