P3449 [POI2006]PAL-Palindromes 题解
Utilokasteinn · · 题解
题目大意:有
注意,给出的全都是回文串。
首先容易发现,回文串的循环节一定是回文串。
所以当
证明:
若回文串
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 是由x 个回文串s1 组成,回文串b 是由s2 个回文串v 组成。
若相接要回文,及
s1 要与s2 的后缀回文(假设len_s1\le len_s2 )。显然,s1 不可能为s2 的循环节,那s1 也就肯定不可能与s2 回文,及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;
}