[SP1811] LCS - Longest Common Substring - 后缀自动机

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);
}


猜你喜欢

转载自www.cnblogs.com/mollnn/p/13174124.html
今日推荐