回文树模板 hdu3948

题目链接:https://vjudge.net/problem/HDU-3948
题意:输出每个串有多少个子串是回文串
题目解析转自:http://www.pianshen.com/article/86272661/
回文树讲解:https://blog.csdn.net/u013368721/article/details/42100363
输入字符串后必须先用strlen函数把长度算出来在用for循环,如果直接将strlen(s)放在循环里会超时.
因为一开始就有了两个节点,添加节点时从2开始,最后p++,所以输出是应该-2.
还有注意节点与字符的区别 一个节点一定是回文串。若添加一个字符时并不能构成回文串或者该回文串已经存在,则不会添加新的节点,len数组与cnt数组num数组都不会更新。

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005 ;
const int N = 26 ;
char s[MAXN];
struct Palindromic_Tree
{
    int next[MAXN][N] ;//next指针,next指针和字典树类似,指向的串为当前串两端加上同一个字符构成
    int fail[MAXN] ;//fail指针,失配后跳转到fail指针指向的节点
    int cnt[MAXN] ;//在最后统计后它可以表示以节点i为结尾的回文串中最长的串个数 必须调用count之后才可以
    int num[MAXN] ;//表示以节点i表示的最长回文串的最右端点为回文串结尾的回文串个数
    int len[MAXN] ;//len[i]表示以节点i结尾的最长回文串的长度
    int S[MAXN] ;//存放添加的字符
    int last ;//指向上一个字符所在的节点,方便下一次add
    int n ;//字符数组指针
    int p ;//节点指针

    int newnode ( int l )  //新建节点
    {
        for ( int i = 0 ; i < N ; ++ i )
            next[p][i] = 0 ;
        cnt[p] = 0 ;
        num[p] = 0 ;
        len[p] = l ;
        return p ++ ;
    }

    void init ()  //初始化
    {
        p = 0 ;
        newnode (  0 ) ;
        newnode ( -1 ) ;
        last = 0 ;
       n = 0 ;
        S[n] = -1 ;//开头放一个字符集中没有的字符,减少特判
        fail[0] = 1 ;
    }

    int get_fail ( int x )  //和KMP一样,失配后找一个尽量最长的
    {
        while ( S[n - len[x] - 1] != S[n] )
            x = fail[x] ;
        return x ;
    }

    int add ( int c )//返回以当前字符为结尾的最长回文串长度
    {
        c -= 'a' ;
        S[++ n] = c ;
        int cur = get_fail ( last ) ;//通过上一个回文串找这个回文串的匹配位置
        if ( !next[cur][c] )  //如果这个回文串没有出现过,说明出现了一个新的本质不同的回文串
        {
            int now = newnode ( len[cur] + 2 ) ;//新建节点
            fail[now] = next[get_fail ( fail[cur] )][c] ;//和AC自动机一样建立fail指针,以便失配后跳转
            next[cur][c] = now ;
            num[now] = num[fail[now]] + 1 ;
        }
        last = next[cur][c] ;
        cnt[last] ++ ;
        return len[last];
    }

    void count ()
    {
        for ( int i = p - 1 ; i >= 0 ; -- i )
            cnt[fail[i]] += cnt[i] ;
        //父亲累加儿子的cnt,因为如果fail[v]=u,则u一定是v的子回文串!
    }
} ;
Palindromic_Tree tree;
int main()
{
    int T,cnt=0;
    scanf("%d",&T);
    while(T--)
    {
        tree.init();
        scanf("%s",s);
        int l=strlen(s);
        for(int i=0; i<l; i++)
        {
            tree.add(s[i]);
        }
        printf("Case #%d: %d\n",++cnt,tree.p-2);
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值