19 ICPC 徐州网络赛 G. Colorful String(回文树)

传送门

题意:求出给出的字符串中所有回文字符串的不同字符和。

思路:回文树+二进制表示字符 (例如 a==1<<0,b==1<<1,c==1<<2,d==1<<3)期间 | 运算(有1则1).

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <map>
#include <iterator>
#include <vector>
#include <set>
#include <bitset>
#include <stack>
#define mems(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int N=3e5+5;
struct node
{
    ll fail,len,cnt,nu,son[26];
}se[N];
char s[N];
ll tot,last;
void init()
{
    tot=0;last=1;
    se[tot++].len=0;
    se[tot].len=-1;
    se[0].fail=1;
    se[1].fail=1;
}
ll get_fail(ll x,ll id)//x last地址
{
    while(s[id]!=s[id-se[x].len-1])
    {
        x=se[x].fail;
    }
    return x;
}
void add(ll x,ll id)
{
    last=get_fail(last,id);
    if(!se[last].son[x])
    {
        se[++tot].len=se[last].len+2;
        se[tot].cnt=se[last].cnt|(1<<x);
        se[tot].fail=se[get_fail(se[last].fail,id)].son[x];
        se[last].son[x]=tot;
    }
    last=se[last].son[x];
    se[last].nu++;
}
ll tao(ll x)
{
    ll ans=0;
    while(x)
    {
        if(x&1)
        {
            ans++;
        }
        x>>=1;
    }
    return ans;
}
ll query()
{
    ll sum=0;
    for(ll i=tot;i>1;i--)
    {
       se[se[i].fail].nu+=se[i].nu;
       sum+=se[i].nu*tao(se[i].cnt);
    }
    return sum;
}
int main()
{
    scanf("%s",s);
    init();
    ll len=strlen(s);
    for(ll i=0;i<len;i++)
    {
        ll x=(ll)(s[i]-'a');
        add(x,i);
    }
    printf("%lld\n",query());
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值