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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章