SPOJ LCS (后缀自动机)

SPOJ LCS

Problem : 给两个串S、T,询问两个串的最长公共子串。
Solution :复(yu)习(xi)了一下后缀自动机。后缀自动机一定要结合后缀树来理解呀 !!!后缀自动机的fail指针实现了原串的逆序的后缀树,后缀自动机的nt转移数组相当于后缀树上的后缀链。

#include <iostream>
#include <string>

using namespace std;

const int N = 250008;

struct Suffix_Automaton
{
    int nt[N << 1][26], fail[N << 1], a[N << 1];
    int p, q, np, nq;
    int tot, last, root;
    int newnode()
    {
        for (int i = 0; i < 26; ++i) nt[tot][i] = -1;
        fail[tot] = -1; a[tot] = 0;
        return tot++;
    }
    void clear()
    {
        tot = last = 0; 
        root = newnode();
    }
    void insert(int ch)
    {
        p = last; last = np = newnode(); a[np] = a[p] + 1;
        for (; ~p && nt[p][ch] == -1; p = fail[p]) nt[p][ch] = np;
        if (p == -1) fail[np] = root;
        else
        {
            q = nt[p][ch];
            if (a[q] == a[p] + 1) fail[np] = q;
            else
            {
                nq = newnode();
                for (int i = 0; i < 26; ++i) nt[nq][i] = nt[q][i];  //i不要打成ch
                fail[nq] = fail[q]; fail[q] = fail[np] = nq;   //第一句 fail[q] 不一定等于p, nq是复制q的出边
                a[nq] = a[p] + 1;
                for (; ~p && nt[p][ch] == q; p = fail[p]) nt[p][ch] = nq;
            }
        }
    }
    void solve(const string &s)
    {
        int p = root, cnt = 0, ans = 0;
        for (int i = 0, len = s.length(); i < len; ++i)
        {
            int ch = s[i] - 'a';
            if (~nt[p][ch]) p = nt[p][ch], cnt++;
            else
            {
                for(; ~p && nt[p][ch] == -1; p = fail[p]);
                if (p == -1) p = root, cnt = 0;
                else cnt = a[p] + 1, p = nt[p][ch];
            }
            ans = max(ans, cnt);
        }
        cout << ans << endl;
    }
}sam;

int main()
{
    cin.sync_with_stdio(0);
    string s, t;
    while (cin >> s >> t)
    {
        sam.clear();
        for (int i = 0, len = s.length(); i < len; ++i)
            sam.insert(s[i] - 'a');
        sam.solve(t);
    }
}

转载于:https://www.cnblogs.com/rpSebastian/p/7217029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值