NOIP2020 T2
今天模拟赛 vp NOIP2020,赛时想到一个很复杂度很神奇的做法。
下面给出复杂度
约定:下文字符串使用
部分题解提到的暴力做法是
暴力做法具体是,对于每个串
-
如果
p_i \nmid i 则s_{1 \sim i} 没有整周期,只有\left(X = s_{1 \sim i}\right)C 这一种划分。 -
否则
p_i 的因数都是可能的划分,可以得到s_{1 \sim i} = {s_{1 \sim p_i}}^{\left(\frac{i}{p_i}\right)} ,也就是s_{1 \sim i} 由\left(\frac{i}{p_i}\right) 个最小周期s_{1 \sim p_i} 组成;将
\left(\frac{i}{p_i}\right) 简称为z ,对于z 的因数d ,可以令\left(X = x^d\right)^{\left( \frac{z}{d} \right)}C ,这样X 总共有O(\tau(z)) 种。
这样,我们将问题转化成若干形如
注意到
对于询问
于是乎,时间复杂度是
这个我场上认为是
我们忽略
代码出乎意料的好写。
#include <bits/stdc++.h>
// #pragma GCC optimize("Ofast")
using namespace std;
using uint = unsigned int; using ll = long long; using ull = unsigned long long;
using pii = pair<int, int>; using pll = pair<ll, ll>;
using ld = long double; using i128 = __int128; using u128 = unsigned __int128;
template<typename T, size_t N, size_t M> using matrix = array<array<T, M>, N>;
template<typename T1, typename T2> bool chkmin(T1& a, const T2& b) { return b < a ? (a = b, true) : false; }
template<typename T1, typename T2> bool chkmax(T1& a, const T2& b) { return b > a ? (a = b, true) : false; }
template<class... T> void debug(T&&... x) { cout << "(debug) "; ((cout << x << " "), ...); cout << "\n"; }
void fileIO(const string& x) { freopen((x + ".in").c_str(), "r", stdin), freopen((x + ".out").c_str(), "w", stdout); }
mt19937_64 gen(random_device{}());
ll test_num = 1, test_case = 1;
const int int_Inf = 1e9; const ll Inf = 1e18;
const ll N = (1 << 20) + 5;
int n, cnt[26], pre[N], suf[N], bd[N], sum[N][27]; // sum_{p, x} := G(p, z)
string s;
vector<int> P[N];
void solution() {
cin >> s; n = s.size(); s = '#' + s;
fill(cnt, cnt + 26, 0);
for(int i = 1; i <= n; i++) { // pre_i := F(s_{1 ~ i})
pre[i] = 0, cnt[s[i] - 'a']++;
for(int c = 0; c < 26; c++) pre[i] += (cnt[c] % 2 == 1);
for(int x = 0; x <= 26; x++) sum[i][x] = sum[i - 1][x] + (pre[i] <= x);
}
fill(cnt, cnt + 26, 0);
for(int i = n; i >= 1; i--) { // suf_i := F(s_{i ~ n})
suf[i] = 0, cnt[s[i] - 'a']++;
for(int c = 0; c < 26; c++) suf[i] += (cnt[c] % 2 == 1);
}
bd[0] = 0; // 求 border 长度
for(int i = 1; i <= n; i++) {
ll p = i - 1;
while(p != 0 && s[bd[p] + 1] != s[i]) p = bd[p];
bd[i] = p == 0 ? 0 : bd[p] + 1;
}
ll ans = 0;
for(int i = 1; i < n; i++) {
ll k = i - bd[i], z = i / k, x = suf[i + 1];
// k: 最小周期长度
// z: s_{1 ~ i} 由 z 个最小周期 s_{1 ~ k} 组成
// x: F(C) = x
if(i % k != 0) {
ans += sum[i - 1][x];
} else {
for(auto d : P[z]) { // P[x] : 集合 {d : d | x}
ans += sum[d * k - 1][x];
}
}
}
cout << ans << "\n";
}
void prework() { // 预处理因数集合
for(int d = 1; d < N; d++) {
for(int x = d; x < N; x += d) {
P[x].emplace_back(d);
}
}
}
int main() {
// fileIO("string");
ios::sync_with_stdio(false), cin.tie(nullptr);
prework();
cin >> test_num;
for(test_case = 1; test_case <= test_num; test_case++) solution();
cerr << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
return 0;
}
这份代码常数略大,std::vector 换成内存池才可以通过,但是代码的可读性较差,就不放在题解内了。优化版本参见 Link。