后缀自动机

#define CLR(x) memset(x,0,sizeof(x))
const int M = 1e5+5;
char str[M];

struct Suffix_Automaton{
    static const int NODE=M<<1, C=26;
    int allc, last, pre[NODE], len[NODE], trans[NODE][C];

    int Create()
    {
        int ret = ++allc;
        memset(trans[ret], 0, C<<2);
        return ret;
    }

    void Init()
    {
        allc = 0;
        last = Create();
        pre[last] = len[last] = 0;
    }

    void Insert(int c)
    {
        int p = last;
        int np = Create();
        len[np] = len[last] + 1;

        while(p && trans[p][c]==0)
        {
            trans[p][c] = np;
            p = pre[p];
        }

        if (!p) pre[np] = 1;
        else
        {
            int q = trans[p][c];
            if (len[q] == len[p]+1) pre[np] = q;
            else
            {
                int nq = ++allc;
                pre[nq] = pre[q];
                len[nq] = len[p] + 1;
                memcpy(trans[nq], trans[q], C<<2);
                pre[np] = pre[q] = nq;

                for (trans[p][c]=nq, p=par[p]; p&&trans[p][c]==q; p=pre[p])
                    trans[p][c] = nq;
            }
        }
        last = np;
    }

    void cons()
    {
        Init();
        int len = strlen(str);
        for (int i = 0; i < len; i++)
            Insert(str[i]-'a');
    }
};

你可能感兴趣的:(后缀自动机)