题解 P3449 【[POI2006]PAL-Palindromes】

· · 题解

定义新运算 p \times S(p 为正整数,S 为字符串)为 S 连写 p 遍。

先说结论:如果 A, B, A+B 均为回文串,则 A 和 B 的循环节相同。

也就是说,存在 C,使得 A = a \times C, B = b \times C

我看过这道题的题解,都用了这个结论,可惜没有人有严谨(?)证明

下面是证明:

使用数学归纳法证明。

定义命题 P(a, b) 为:

对于任意两个分别长为 a, b 的回文串 A, B,如果 A+B 为回文串,则必定存在 C,使得 A = p \times C, B= q \times C

首先 P(a, a) 显然成立。

现在证明当 P(a, b) 时,P(a, a+b) 必然成立。

证明:(Pal(S) 表示 S 是回文串)

len(A) = a, len(C) = a + b \text{设 C 的前 b 位为 B,后 a 位为 D} \therefore Pal(A), Pal(B+D), Pal(A+B+D) \because len(A) = len(D), Pal(A+B+D), \therefore A=D, Pal(B), Pal(D) \because \begin{cases}len(B) = b \\ len(D) = a \\ Pal(B) \\ Pal(D) \\ Pal(B+D) \\ P(b, a)\end{cases} B = p \times S, D = q \times S \because A = D, \therefore A = q \times S \because C = B + D, \therefore C = p \times S + q \times S = (p+q) \times S \therefore\begin{cases}A = q \times S \\ C = (p+q) \times S\end{cases} \therefore P(a, a+b)

所以我们知道:

\begin{cases}P(a, a) \\ P(a, b) \Rightarrow P(a, a+b)\end{cases} \Rightarrow P(a, b) \Huge{\mathcal{Q.E.D.}}

于是我们只需要找出每一个字符串的最短循环节即可。

枚举字符串长度的因子,求出分出的每段子串的哈希值,判断是否相等即可。

注意一点:两数相减可能为负,此时应当 \%mod,再 +mod,再 \%mod。

最后排一下序,把循环节相同的分为一组,由于每组内可以随意配对,所以最终答案即为每组元素个数的平方和。

还有,答案要开 long long!

时间复杂度约为 \Theta(n \log n)。其实我也算不清楚

你们最想看的代码,他来了!

#include <bits/stdc++.h>
#define mod 1000000007ll
#define base 233ll
using namespace std;
int n, len;
long long cnt, sum;
int pows[2000010];
int hash[2000010];
string str, ans[2000010];

int main() {
    pows[0] = 1;
    for (int i = 1; i <= 2000000; i++) {
        pows[i] = (long long) pows[i-1] * base % mod;
    }
    cin >> n;
    for (int a = 1; a <= n; a++) {
        cin >> len >> str;
        hash[0] = str[0];
        for (int i = 1; i < len; i++) {
            hash[i] = (hash[i-1] + (long long)pows[i] * str[i]) % mod;
        }
        for (int i = 1; i <= len; i++) {
            if (len % i) continue;
            int t = hash[i-1];
            for (int j = i*2; j <= len; j += i) {
                t = (long long)t * pows[i] % mod;
                if (t != (hash[j-1] - hash[j-i-1] + mod) % mod) goto fail;
            }
            ans[a] = str.substr(0, i);
            break;
            fail:;
        }
    }
    sort(ans+1, ans+n+1);
    for (int i = 1; i <= n; i++) {
        if (ans[i] == ans[i-1]) cnt++;
        else sum += cnt * cnt, cnt = 1;
    }
    sum += cnt * cnt;
    cout << sum << endl;
    return 0;
}