SPOJ NUMOFPAL 回文树

本文介绍了一种使用回文树解决求字符串中本质不同回文子串数目的方法。通过构建回文树并利用其特性进行计数,最终得出所有不同回文子串的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接点我点我:-)

题目描述
给一个字符串,求其本质不同的回文子串数目(字符串长度<=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][30], pre[N], len[N], cnt[N], Tot, last;

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

    int getfail(int id, int nl){
        while(s[id-len[nl]-1] != 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]+2;
            pre[p] = ch[getfail(id, pre[nl])][c];
            if(pre[p] == p) pre[p] = 0;
        }

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

    void Count(){
        Forr(i, Tot, 2) cnt[pre[i]] += cnt[i];
        For(i, 2, 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+1); s[0] = 27;

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

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值