这是一个SAM板子

如题

  • 代码
#include<bits/stdc++.h>
using namespace std;
const int N=2e6+5,SZ=26;

struct SuffixAutomaton
{
    struct NODE{
        int ch[SZ],fa;
        int len,right;
    }t[N];
    int root,last,cnt;
    inline int newnode(int _len){
        t[++cnt].len=_len;
        return cnt;
    }
    inline void init(){//"初始化
        root=last=newnode(0);
    }
    inline void ins(int c)//"c=(char)-'a';
    {
        int nq=newnode(t[last].len+1),q=last;
        for(;q&&!t[q].ch[c];q=t[q].fa)t[q].ch[c]=nq;
        if(q==0) t[nq].fa=root;
        else if(t[t[q].ch[c]].len==t[q].len+1)t[nq].fa=t[q].ch[c];
        else{
            int np=newnode(t[q].len+1),p=t[q].ch[c];
            memcpy(t[np].ch,t[p].ch,sizeof(t[p].ch));
            t[np].fa=t[p].fa;
            t[p].fa=t[nq].fa=np;
            for(;q&&t[q].ch[c]==p;q=t[q].fa)t[q].ch[c]=np;
        }
        t[nq].right=1,last=nq;
    }
    int topo[N],buc[N];
    inline void toposet(){
        int mx=0;
        for(int i=1;i<=cnt;i++)buc[t[i].len]++,mx=max(mx,t[i].len);
        for(int i=1;i<=mx;i++)buc[i]+=buc[i-1];
        for(int i=1;i<=cnt;i++)topo[buc[t[i].len]--]=i;
    }
    inline void cal_right()
    {
        toposet();
        for(int i=cnt;i;i--){
            int cur=topo[i];
            t[t[cur].fa].right+=t[cur].right;
        }
    }
}SAM;
char str[N];
int main()
{
    SAM.init();
    scanf("%s",str+1);
    int len=strlen(str+1);
    for(int i=1;i<=len;i++)SAM.ins(str[i]-'a');
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35923186/article/details/82828927