【回文树】HDU - 6599 - I Love Palindrome String

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=6599


题意

给出一个字符串,统计有长度为1~n好串的个数。
好串的定义为:本身是回文串,左半边也是回文串。


题解

先用回文树跑一遍,对于每个本质不同的回文串进行判断,累加答案即可。至于判断,可以用马拉车等方法。但观察一下也可以发现,如果当前串长 t 1 t1 t1,和最长后缀回文串长 t 2 t2 t2满足关系: ( t 1 / 2 ) % ( t 1 − t 2 ) = = 0 (t1/2)\%(t1-t2)==0 (t1/2)%(t1t2)==0,该串就是好串。
参考大佬博客:https://www.cnblogs.com/Chen-Jr/p/11240112.html


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e5+7;
struct PAM{//回文树
    int nxt[N][26],fail[N],len[N],cnt[N],str[N];
    int tot,n,lst;
    int newnode(int x){
        for(int i=0;i<26;i++) nxt[tot][i]=0;
        cnt[tot]=0;
        len[tot]=x;
        return tot++;
    }
    void init(){
        tot=lst=n=0;
        newnode(0);
        newnode(-1);
        fail[0]=1;
        str[0]=-1;
    }
    int getfail(int x){
        while(str[n-len[x]-1]!=str[n]) x=fail[x];
        return x;
    }
    void ist(int c){
        str[++n]=c;
        int cur=getfail(lst);
        if(!nxt[cur][c]){
            int now=newnode(len[cur]+2);
            fail[now]=nxt[getfail(fail[cur])][c];
            nxt[cur][c]=now;
        }
        lst=nxt[cur][c];
        cnt[lst]++;
    }
    void getsum(){
        for(int i=tot-1;i>=0;i--){
            cnt[fail[i]]+=cnt[i];
        }
    }
}pam;
char s[N];
int ans[N];
bool ck(int x){
    int t1=pam.len[x];
    int t2=pam.len[pam.fail[x]];
    return ((t1/2)%(t1-t2))==0;
}
int main(){
    while(scanf("%s",s)!=EOF){
        pam.init();
        int sz=strlen(s);
        for(int i=0;i<sz;i++){
            pam.ist(s[i]-'a');
            ans[i+1]=0;
        }
        pam.getsum();
        for(int i=0;i<pam.tot;i++){
            if(ck(i)) ans[pam.len[i]]+=pam.cnt[i];
        }
        for(int i=1;i<=sz;i++){
            printf("%d%c",ans[i],i==sz?'\n':' ');
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值