• 【后缀数组】【SP1811】 LCS


    题目链接

    题意翻译

    输入2 个长度不大于250000的字符串,输出这2 个字符串的最长公共子串。如果没有公共子串则输出0 。

    思路

    求两个串的最长公共子串

    代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define maxn 500010
    using namespace std;
    
    int n, n1, n2;
    
    char s1[maxn], s2[maxn], s[maxn]; 
    
    int tax[maxn], rk[maxn], tp[maxn], sa[maxn], M = 200; 
    void rsort() {
        for (int i = 0; i <= M; ++i) tax[i] = 0;
        for (int i = 1; i <= n; ++i) ++tax[rk[i]];
        for (int i = 1; i <= M; ++i) tax[i] += tax[i - 1];
        for (int i = n; i; --i) sa[tax[rk[tp[i]]]--] = tp[i]; 
    }
    
    int H[maxn]; 
    void SA() {
        for (int i = 1; i <= n; ++i) rk[i] = s[i], tp[i] = i; 
        int c1 = 0; rsort();
        for (int k = 1; k <= n; k *= 2) {
            if (c1 == n) break; M = c1; c1 = 0; 
            for (int i = n - k + 1; i <= n; ++i) tp[++c1] = i;
            for (int i = 1; i <= n; ++i) if (sa[i] > k) tp[++c1] = sa[i] - k;
            rsort(); swap(tp, rk); rk[sa[1]] = c1 = 1;
            for (int i = 2; i <= n; ++i) {
                if (tp[sa[i - 1]] != tp[sa[i]] || tp[sa[i - 1] + k] != tp[sa[i] + k]) ++c1;
                rk[sa[i]] = c1; 
            }
        }
        int lcp = 0;
        for (int i = 1; i <= n; ++i) {
            if (lcp) --lcp;
            int j = sa[rk[i] - 1];
            while (s[j + lcp] == s[i + lcp]) ++lcp;
            H[rk[i]] = lcp; 
        }
    }
    
    int ans;
    int main() {
        scanf("%s%s", s1 + 1, s2 + 1);
        n = n1 = strlen(s1 + 1); n2 = strlen(s2 + 1);
        for (int i = 1; i <= n1; ++i) s[i] = s1[i];
        s[++n] = '$';
        for (int i = 1; i <= n2; ++i) s[++n] = s2[i]; SA();
        for (int i = 2; i <= n; ++i) {
            int x = sa[i], y = sa[i - 1];
            if (x > y) swap(x, y);
            if (x <= n1 && y > n1 + 1) ans = max(ans, H[i]); 
        } cout << ans << endl; 
        return 0; 
    }
    
  • 相关阅读:
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    以太坊:通信协议对象 shh
    以太坊:Truffle 概述
    以太坊:快速入门 Truffle
  • 原文地址:https://www.cnblogs.com/duzhiyuan/p/11938297.html
Copyright © 2020-2023  润新知