HDU 4622 (後綴自動機)

HDU 4622 Reincarnation

Problem : 給一個串S(n <= 2000), 有Q個詢問(q <= 10000),每次詢問一個區間內本質不一樣的串的個數。
Solution : 因爲n只有2000,對串S的每個左端點創建一遍後綴自動機,暴力計算出全部答案的值。。。node

#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;
        }
    }
}
相關文章
相關標籤/搜索