The Preliminary Contest for ICPC Asia Xuzhou 2019: G. Colorful String(回文自动机):

题目链接:点击这里

因为长度为n的字符串的本质不同的回文串的级别是O(n)的。
所以我们直接跑回文自动机然后枚举所有本质不同的子回文串即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<cmath>
#define ll long long
#define llu unsigned ll
using namespace std;
const double eps = 1e-8;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const ll lnf=0x3f3f3f3f3f3f3f3f;
const int maxn=300015 ;
const int N=26 ;
char str[maxn];
int ha[100];
ll ans=0;

struct Palindromic_Tree {
    int next[maxn][N];
    int fail[maxn];
    int cnt[maxn];
    int num[maxn];
    int len[maxn];
    int S[maxn];
    int last;
    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)
    {
        while(S[n-len[x]-1]!=S[n]) x=fail[x];
        return x;
    }

    void 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];
            next[cur][c]=now;
            num[now]=num[fail[now]]+1;
        }
        last=next[cur][c];
        cnt[last]++;
    }

    void _count()
    {
        for(int i=p-1;i>=0;--i) cnt[fail[i]]+=cnt[i];
    }


} pam;

void dfs(int x,int cnt)
{
    for(int i=0;i<26;i++)
    {
        int pm=cnt;
        if(pam.next[x][i])
        {
             ha[i]++;
             if(ha[i]==1) pm=cnt+1;
             ans+=(ll)pm*pam.cnt[pam.next[x][i]];
             dfs(pam.next[x][i],pm);
             ha[i]--;;
        }
    }
}


int main(void)
{
    scanf("%s",str);
    int len=strlen(str);
    memset(ha,0,sizeof(ha));
    ans=0;
    pam.init();
    for(int i=0;i<len;i++)
        pam.add(str[i]);
    pam._count();
    dfs(0,0);
    dfs(1,0);
    printf("%lld\n",ans);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值