SAM模板

· · 个人记录

struct SAM
{
    struct node
    {
        int link,len;
        map<int,int> ch;
    }t[MAXN<<1];
    int last,sz;
    void new_node(int length)
    {
        t[++sz].len=length;
        t[sz].link=-1;
        t[sz].ch.clear();
    }
    SAM()
    {
        last=0,sz=-1;
        new_node(0);
    }
    void insert(int c)
    {
        new_node(t[last].len+1);
        int p=last,cur=sz;
        while(p!=-1&&!t[p].ch[c])
        {
            t[p].ch[c]=cur;
            p=t[p].link;
        }
        if(p==-1)
        {
            t[cur].link=0;
        }
        else
        {
            int q=t[p].ch[c];
            if(t[q].len==t[p].len+1) 
            {
                t[cur].link=q;
            }
            else
            {
                new_node(t[p].len+1);
                int nq=sz;
                t[nq].ch=t[q].ch;
                t[nq].link=t[q].link;
                t[cur].link=t[q].link=nq;
                while(p!=-1&&t[p].ch[c]==q)
                {
                    t[p].ch[c]=nq;
                    p=t[p].link;
                }
            }
        }
        last=cur;
    }
}sam;
struct SAM
{
    struct node
    {
        int link,len;
        int ch[26];
    }t[MAXN<<1];
    int last,sz;
    void new_node(int length)
    {
        t[++sz].len=length;
        t[sz].link=-1;
        memset(t[sz].ch,0,sizeof(t[sz].ch));
    }
    SAM()
    {
        last=0,sz=-1;
        new_node(0);
    }
    void insert(int c)
    {
        new_node(t[last].len+1);
        int p=last,cur=sz;
        while(p!=-1&&!t[p].ch[c])
        {
            t[p].ch[c]=cur;
            p=t[p].link;
        }
        if(p==-1)
        {
            t[cur].link=0;
        }
        else
        {
            int q=t[p].ch[c];
            if(t[q].len==t[p].len+1) 
            {
                t[cur].link=q;
            }
            else
            {
                new_node(t[p].len+1);
                int nq=sz;
                memcpy(t[nq].ch,t[q].ch,sizeof(t[q].ch));
                t[nq].link=t[q].link;
                t[cur].link=t[q].link=nq;
                while(p!=-1&&t[p].ch[c]==q)
                {
                    t[p].ch[c]=nq;
                    p=t[p].link;
                }
            }
        }
        last=cur;
        dp[cur]=1;
    }
}sam;