❤️题目大意
题目是求 S = (AB)iC 的方案数,其中 F(A) ≤ F©,F(S ) 表示字符串 S中出现奇数次的字符的数量。
❤️解题思路
先确定好C的可能,即末尾几位字符。然后再考虑划分(AB)i,需要找出(AB)i的最小重复子串,相关算法考虑KMP算法或者字符串哈希,再在该子串中划分A和B,产生方案。
需要注意的是AB不一定只能存在于最小的重复子串中。比如:
(AB)i = abababababab,最小重复是 ab,但重复的部分也可以是 abab,同样可以在abab中划分AB串,另外还有ababab以及整个(AB)i。分别是最小重复串的1、2、3、6倍,都是最大重复次数6的约数。
另外定好(AB)的范围后,划分AB时注意题目限制F(A) ≤ F©。
❤️参考代码
#include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const ll N = 1100000, base1 = 1021831, base2 = 96269;
ull hash1[N], hash2[N], pow1[N], pow2[N];
ull f1(ll l, ll r) {
return hash1[r] - hash1[l - 1] * pow1[r - l + 1];
}
ull f2(ll l, ll r) {
return hash2[r] - hash2[l - 1] * pow2[r - l + 1];
}
pair<ull, ull> f(ll l, ll r) {
return make_pair(f1(l,r), f2(l,r));
}
struct BIT {
ll sum[30], n;
void clear() {
memset(sum, 0, sizeof(sum));
}
inline ll lowbit(ll x) {
return x & (-x);
}
void add(ll x, ll v) {
while (x <= n) {
sum[x] += v; x += lowbit(x);
}
}
ll find(ll x) {
ll ans = 0;
while(x) {
ans += sum[x]; x -= lowbit(x);
}
return ans;
}
} T;
ll book[30], tot[N], num[N];
char ch[N];
int main() {
ll ans = 0, cnt = 0;
ll Q; cin >> Q; T.n = 26;
while (Q--) {
T.clear();
memset(book, 0, sizeof(book)); memset(tot, 0, sizeof(tot)); memset(num, 0, sizeof(num));
cnt = ans = 0;
cin >> ch + 1; int n = strlen(ch + 1);
hash1[0] = hash2[0] = 0; pow1[0] = pow2[0] = 1;
for (int i = 1; i <= n; ++i) {
hash1[i] = hash1[i - 1] * base1 + ch[i]; hash2[i] = hash2[i - 1] * base2 + ch[i];
pow1[i] = pow1[i - 1] * base1; pow2[i] = pow2[i - 1] * base2;
}
for (int i = n; i >= 3; --i) {
book[ch[i] - 'a'] ^= 1;
if (!book[ch[i] - 'a']) {
tot[i] = --cnt;
} else {
tot[i] = ++cnt;
}
}
num[n - 1] = 1;
for (int i = n - 2; i >= 2; --i) {
if (i * 2 > n - 1 || f(1, i) != f(i + 1, i * 2)) {
num[i] = 1;
continue;
}
num[i] = num[i << 1] << 1;
if (num[i] * i + i <= n - 1 && f(1, i) == f(num[i] * i + 1, num[i] * i + i)) {
++num[i];
}
}
cnt = 0; memset(book, 0, sizeof(book));
for (int i = 2; i < n; ++i) {
book[ch[i - 1] - 'a'] ^= 1;
if (!book[ch[i - 1] - 'a']) {
--cnt;
} else {
++cnt;
}
T.add(cnt + 1, 1);
ans += T.find(tot[i + 1] + 1) * ((num[i] >> 1) + (num[i] & 1)) + T.find(tot[i * 2 + 1] + 1) * (num[i] >> 1);
}
cout << ans << '\n';
}
return 0;
}