天天看点

SPOJ NUMOFPAL 回文树

题目链接:点我点我:-)

题目描述:

给一个字符串,求其本质不同的回文子串数目(字符串长度<=1000)

思路:

这是一个非常好的讲解

建立回文树,每次在最后停留的节点上计数器加一,

最后从父亲累加儿子的cnt,因为如果pre[v]=u,则u一定是v的子回文串

代码:

//miaomiao 2017.3.25
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>

using namespace std;

#define For(i, a, b) for(int i = (a); i <= (int)(b); ++i)
#define Forr(i, a, b) for(int i = (a); i >= (int)(b); --i)
#define N (1000+5)

char s[N];
int ans;

struct Palin_Tree{
    int ch[N][], pre[N], len[N], cnt[N], Tot, last;

    void init(){
        Tot = ; last = ;
        len[] = -; pre[] = ;
    }

    int getfail(int id, int nl){
        while(s[id-len[nl]-] != s[id]) nl = pre[nl];
        return nl;
    }

    void Add(int id, char c){
        c -= 'a';

        int nl = getfail(id, last);
        if(!ch[nl][c]){
            int p = ch[nl][c] = ++Tot;
            len[p] = len[nl]+;
            pre[p] = ch[getfail(id, pre[nl])][c];
            if(pre[p] == p) pre[p] = ;
        }

        last = ch[nl][c]; ++cnt[last];
    }

    void Count(){
        Forr(i, Tot, ) cnt[pre[i]] += cnt[i];
        For(i, , Tot) ans += cnt[i];
        printf("%d\n", ans);
    }
}PT;

int main(){
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif

    PT.init();
    scanf("%s", s+); s[] = ;

    For(i, , strlen(s+)) PT.Add(i, s[i]);
    PT.Count();

    return ;
}