【题目链接】
【思路要点】
- 枚举对称中心,设关于该中心对称点的个数为\(x\),以该点为中心的最长回文子串长度为\(y\),那么该点对答案的贡献应为\(2^x-\lfloor\frac{y+1}{2}\rfloor\)。
- 其中对称点的个数可以通过FFT或bitset压位求出,最长回文子串长度可以用Manacher算法求出。
- 时间复杂度\(O(\frac{N^2}{w})\)或\(O(NLogN)\)。
【代码】
#include<bits/stdc++.h> using namespace std; #define QLEN 64 #define MAXN 100005 #define P 1000000007 bitset <QLEN> front[MAXN], back[MAXN]; char s[MAXN], x[MAXN*2]; int len[MAXN*2]; long long num[MAXN]; int main() { scanf("%s", s+1); int n = strlen(s+1); for (int i = 1; i <= n; i++) for (int j = 0; j<QLEN; j++) { if (i-j >= 1) if (s[i-j] == 'a') front[i].set(j); else front[i].reset(j); if (i+j <= n) if (s[i+j] == 'b') back[i].set(j); else back[i].reset(j); } num[0] = 1; for (int i = 1; i <= n; i++) num[i] = num[i-1]*2%P; for (int i = 0; i <= n; i++) num[i]--; long long ans = 0; int tn = n-QLEN; for (int i = 1; i <= n; i++) { int j = i, k = i, l = i+1, cnt = 0, cmt = 0; while (j >= QLEN && k <= tn && l <= tn) { cnt += (front[j]^back[k]).count(); cmt += (front[j]^back[l]).count(); j -= QLEN; k += QLEN; l += QLEN; } while (j >= 1 && k <= n) { cnt += s[j] == s[k]; cmt += s[j] == s[l]; j--; k++; l++; } ans += num[cnt]+num[cmt]; } ans %= P; x[0] = '$'; x[1] = '#'; x[2*n+2] = '%'; for (int i = 1; i <= n; i++) {x[i*2] = s[i]; x[i*2+1] = '#'; } int right = 0, pos = 0; for (int i = 1; i <= 2*n+1; i++) { if (i <= right) { int j = pos*2-i; if (len[j]<right-i+1) len[i] = len[j]; else { len[i] = right-i+1; while (x[i+len[i]] == x[i-len[i]]) len[i]++; right = i+len[i]-1; pos = i; } } else { len[i] = 1; while (x[i+len[i]] == x[i-len[i]]) len[i]++; right = i+len[i]-1; pos = i; } } for (int i = 1; i <= 2*n+1; i++) ans -= len[i]/2; printf("%lld\n", (ans%P+P)%P); return 0; }