迴文樹

len[u]表示結點u所表示的迴文串長度,cnt[u]表示結點u所表示的迴文串出現次數,num[u]表示結點u的後綴迴文串個數(包括本身)。node

因爲一個字符串本質不一樣的迴文串最多不超過n個,因此空間開n+2便可,算上每一個結點的26個Next指針,空間複雜度o(26*n)。時間複雜度o(n)。ide

struct PalinTree
{
    int ch[maxn][26],f[maxn];
    int cnt[maxn],num[maxn],len[maxn];
    int s[maxn];
    int last,n,tot;
    int newnode(int l)
    {
        MS0(ch[tot]);
        cnt[tot]=0;
        num[tot]=0;
        len[tot]=l;
        return tot++;
    }
    void init()
    {
        tot=0;
        newnode(0);
        newnode(-1);
        last=0;n=0;
        s[n]=-1;f[0]=1;
    }
    int get_fail(int x)
    {
        while(s[n-len[x]-1]!=s[n]) x=f[x];
        return x;
    }
    void add(int c)
    {
        c-='a';
        s[++n]=c;
        last=get_fail(last);
        if(!ch[last][c]){
            int cur=newnode(len[last]+2);
            f[cur]=ch[get_fail(f[last])][c];
            ch[last][c]=cur;
            num[cur]=num[f[cur]]+1;
        }
        last=ch[last][c];
        cnt[last]++;
    }
    void count()
    {
        for(int i=tot-1;i>=0;i--) cnt[f[i]]+=cnt[i];
    }
};PalinTree pt;
View Code
相關文章
相關標籤/搜索