HDU 4622 (后缀自动机)

本文介绍了解决HDU4622 Reincarnation问题的方法,该问题是关于在一个字符串中查找指定区间内本质不同的子串数量。通过使用后缀自动机进行遍历并计算,为每个询问提供解答。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HDU 4622 Reincarnation

Problem : 给一个串S(n <= 2000), 有Q个询问(q <= 10000),每次询问一个区间内本质不同的串的个数。
Solution : 由于n只有2000,对串S的每一个左端点建立一遍后缀自动机,暴力计算出所有答案的值。。。

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 2008;
const int INF = 2000000008;

struct suffix_automanon
{
    int nt[N << 1][26], fail[N << 1], a[N << 1];
    int tot, last, root, tmp;
    int p, q, np, nq;

    int ans[N][N];
    int newnode(int len)
    {
        for (int i = 0; i < 26; ++i) nt[tot][i] = -1;
        fail[tot] = -1; a[tot] = len;
        return tot++;
    }
    void clear()
    {
        tot = tmp = 0;
        root = last = newnode(0);
    }
    void insert(int ch, int l, int r)
    {
        p = last; last = np = newnode(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[p] + 1 == a[q]) fail[np] = q;
            else
            {
                nq = newnode(a[p] + 1);
                for (int i = 0; i < 26; ++i) nt[nq][i] = nt[q][i];
                fail[nq] = fail[q];
                fail[q] = fail[np] = nq;
                for (; ~p && nt[p][ch] == q; p = fail[p]) nt[p][ch] = nq;
            }
        }
        tmp += a[np] - a[fail[np]];
        ans[l][r] = tmp;
    }       
}sam;

int main()
{
    cin.sync_with_stdio(0);
    int t; cin >> t;
    for (int i = 1; i <= t; ++i)
    {
        string s; cin >> s;
        for (int i = 0, len = s.length(); i < len; ++i)
        {
            sam.clear();
            for (int j = i; j < len; ++j)
                sam.insert(s[j] - 'a', i, j);
        }
        int q;
        cin >> q;
        while (q--)
        {
            int l, r; cin >> l >> r;
            cout << sam.ans[l - 1][r - 1] << endl;
        }
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值