P3449 [POI2006]PAL-Palindromes 题解

· · 题解

题目大意:有 n 个回文串,任选两个回文串收尾相接组成 n^2 个字符串(可以自己于自己组合)。求这 n^2 个字符串中有几个是回文串。

注意,给出的全都是回文串。

首先容易发现,回文串的循环节一定是回文串。

所以当 a ,b 两个回文串的最小循环节一样时, ab 是回文串。

证明:

若回文串 a 是由 x 个回文串 c 组成,回文串 b 是由 y 个回文串 c 组成。则相接后 ab 是由 x+y 个回文串 c 组成。

在字符串 ab 中,第 1 个 c 与第 x+y 个 c 回文时对应,第 2 个 c 与第 x+y-1 个 c 回文时对应,以此推类。

若 x+y 为偶,显然 ab 回文。若 x+y 为奇,则还剩第 (x+y+1)\div2 个 c 无串与它回文。因为 c 本来就是回文串,所以不管 x+y 是偶是奇, ab 都是回文串。

那如果 a ,b 两个回文串的最小循环节不一样时, ab 就一定不是回文串吗?

证明:

若回文串 a 是由 x 个回文串 s1 组成,回文串 b 是由 s2 个回文串 v 组成。

若相接要回文,及 s1 要与 s2 的后缀回文(假设 len_s1\le len_s2)。显然, s1 不可能为 s2 的循环节,那 s1 也就肯定不可能与 s2 回文,及 ab 不回文。

所以当且仅当 a ,b 两个回文串的最小循环节一样时, ab 是回文串。

代码就很好写了:

#include<bits/stdc++.h>
#define ll long long
#define ull unsigned ll
using namespace std;
ull hash[2000100],mul[2000100],base=31;
int n,m;
ll ans;
char s[2000100];
multiset<ull>se;
inline ull cal(int l,int r)
{
    return hash[r]-hash[l-1]*mul[r-l+1];
}
bool solve(int x)
{
    ull now=cal(1,x);
    for(int i=1;i<=m;i+=x)
        if(cal(i,i+x-1)!=now)return false;
    se.insert(now);
    return true;
}
int main()
{
    mul[0]=1;
    scanf("%d",&n);
    for(int i=1;i<=2e6;i++)
        mul[i]=mul[i-1]*base;
    while(n--)
    {
        scanf("%d%se",&m,s+1);
        for(int i=1;i<=m;i++)
            hash[i]=hash[i-1]*base+s[i];
        for(int i=1;i<=m;i++)
        {
            if(m%i)continue;
            if(solve(i))break;
        }
    }
    while(!se.empty())
    {
        ll num=*se.lower_bound(0);
        ll cnt=se.count(num);
        ans+=cnt*cnt;
        se.erase(num);
    }
    printf("%lld",ans);
    return 0;
}