美文网首页
后缀自动机

后缀自动机

作者: Cyril1317 | 来源:发表于2017-08-07 03:47 被阅读0次
    #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');
        }
    };
    

    相关文章

      网友评论

          本文标题:后缀自动机

          本文链接:https://www.haomeiwen.com/subject/zoqglxtx.html