题解:P3526 [POI 2011] OKR-Periodicity
考虑递归构造,记:
我们有:
- 若
|s| = 1 只需构造t = \texttt{0} 。 - 若
s 无 border,构造t = \underbrace{\texttt{000\dots 00}}_{|s| - 1 \text{ 个 } \texttt{0}} \texttt{1} 即可。 - 若有
\operatorname{border}(s) > \frac{|s|}{2} ,那么只需将递归构造|s| = \operatorname{border}(s) 的情况,然后按 border 关系复制到剩下的位。答案的最小性显然。 - 若有
\operatorname{border}(s) \le \frac{|s|}{2} ,那么还是递归构造|s| = \operatorname{border}(s) 的情况,记此时答案串为t' ,构造t = t_1't_2'\dots t_{\operatorname{border}(s)}'\underbrace {\texttt{000\dots 00}}_{n - 2\operatorname{border}(s) \text{ 个 } \texttt{0}}t_1't_2'\dots t_{\operatorname{border}(s)}' ,若不合法,将第n - \operatorname{border}(s) 位修改为\texttt{1} 即可。这样的最小性依旧是显然的,不难发现修改一位后的t 一定满足:不存在长度大于\operatorname{border}(s) 的 border。
感性理解很对,理性证明不会,反正做完了,只有最后一种情况会遍历整串,于是复杂度线性。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
inline ll Read() {
int sig = 1; ll num = 0; char c = getchar();
while(!isdigit(c)) { if(c == '-') sig = -1; c = getchar(); }
while(isdigit(c)) num = (num << 3) + (num << 1) + (c ^ 48), c = getchar();
return num * sig;
}
void Write(ll x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) Write(x / 10);
putchar((x % 10) ^ 48);
}
const int N = 200005;
int n, s[N], a[N], nxt[N], _nxt[N];
void Construct(int n) {
int i, j;
if(!nxt[n]) {
if(n == 1) a[n] = 0;
else { for(i = 1; i <= n; i++) a[i] = (i == n); }
return ;
}
Construct(nxt[n]);
if(nxt[n] > n / 2) { for(i = nxt[n] + 1; i <= n; i++) a[i] = a[i - (n - nxt[n])]; }
else {
for(i = n; i > n - nxt[n]; i--) a[i] = a[i - (n - nxt[n])];
for(i = 2, j = 0; i <= n; i++) {
while(j && a[j + 1] != a[i]) j = _nxt[j];
j += a[j + 1] == a[i], _nxt[i] = j;
}
i = j = n;
while(i || j) {
if(i != j) break;
i = nxt[i], j = _nxt[j];
}
if(i) a[n - nxt[n]] = 1;
}
}
void Solve() {
int i, j; char c = getchar(); n = 0;
while(c < 'A' || c > 'Z') c = getchar();
while(c >= 'A' && c <= 'Z') s[++n] = c - 'A', a[n] = 0, c = getchar();
for(i = 2, j = 0; i <= n; i++) {
while(j && s[j + 1] != s[i]) j = nxt[j];
j += s[j + 1] == s[i], nxt[i] = j;
}
Construct(n);
for(i = 1; i <= n; i++) Write(a[i]);
putchar('\n');
}
int main() {
int T = Read();
while(T--) Solve();
}