题解:AT_agc076_b [AGC076B] Split and Reverse

· · 题解

输出方式很容易让人猜测只需 O(1) 次操作。

不考虑不操作的情况,假设只需一次操作,发现被操作的两个子序列一定是一段前缀 1 加一段后缀 0。

考虑令 C 为 0 的个数并在 i = C 与 i = C + 1 之间画一条分界线。

分界线后的所有 1 一定只会被划分到一个集合,否则分界线前的所有 0 都不可能被划分,并且当分界线前只有 1 时,容易证明存在一种方案满足上述条件。

然后考虑要使剩下的能被分配,必须就要消掉所有不属于 1 前缀的 1,我们能利用的是所有在 0 后缀中且在分界线后的所有 0。

比如(竖杠是分界线):

110{\color{red}11}0{\color{red}11} | 0{\color{green}1}000{\color{green}111}{\color{blue}00}

是不能通过一次操作完成的,因为所有不属于 1 前缀的 1 有 4 个,属于 0 后缀且在分界线之后的 0 只有 2 个。

归纳一下充要条件再推一下,就是分界线前 1 前缀长度大于等于分界线后右边有 1 的 0 的个数(考虑分界线左边的 1 的个数与分界线右边的 0 的个数相等)。

然后再基于“考虑分界线左边的 1 的个数与分界线右边的 0 的个数相等”,发现我们只需要让分界线左边的 1 集中在前缀,或是让分界线右边的 0 集中在后缀就一定可以满足条件了!

我们关注分界线两边较少的一侧,沿着中线对称到另一端,然后把另一端的区间的 0/1 重新分配反转回去,剩下的随意分配,例如考虑上例(黑色的竖杠是分界线,绿色的竖杠沿中线对称后的分界线,红蓝代表一种 A/B 集合):

\color{blue}{\color{red}11}0{\color{red}11}0{\color{red}11}\color{black} | 01{\color{green}|}\color{red}000111{\color{blue}00}

于是做完了,复杂度线性。

#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 = 250005;
int n, cnt, a[N], pos[N];
bool b[N];
void Reverse(bool *b) {
    int i, k = 0;
    for(i = 1; i <= n; i++) if(b[i]) pos[++k] = i;
    for(i = 1; i <= k / 2; i++) swap(a[pos[i]], a[pos[k - i + 1]]);
    for(i = 1, k = 0; i <= n; i++) if(!b[i]) pos[++k] = i;
    for(i = 1; i <= k / 2; i++) swap(a[pos[i]], a[pos[k - i + 1]]);
}
bool Color() {
    int i, x, lst = cnt;
    for(i = 1; i <= n; i++) b[i] = false;
    for(i = 1; i <= cnt; i++) {
        if(!a[i]) break;
        b[i] = true;
    }
    x = i;
    for(i = cnt; i >= x; i--) b[i] = !a[i];
    for(i = cnt + 1; i <= n; i++) if(a[i]) { lst++; while(lst < i) b[lst++] = x > 1, x--; }
    if(x <= 0) return false;
    for(i = lst + 1; i < lst + x; i++) b[i] = true;
    return true;
}
void Report() { for(int i = 1; i <= n; i++) putchar('A' + b[i]); putchar('\n'); }
void Solve() {
    int i; n = Read(), cnt = 0;
    for(i = 1; i <= n; i++) a[i] = Read(), cnt += !a[i];
    for(i = 1; i <= cnt; i++) if(a[i]) break;
    if(i > cnt) printf("0\n");
    else {
        bool t = Color();
        if(t) printf("1\n"), Report();
        else if(cnt >= n - cnt) {
            int t = 0;
            for(i = 1; i <= n - cnt; i++) b[i] = !a[i], t += !a[i];
            for(i = n; i > n - cnt; i--) b[i] = n - i < t;
            printf("2\n"), Report(), Reverse(b), Color(), Report();
        }
        else {
            int t = 0;
            for(i = n; i > n - cnt; i--) b[i] = a[i], t += a[i];
            for(i = 1; i <= n - cnt; i++) b[i] = i <= t;
            printf("2\n"), Report(), Reverse(b), Color(), Report();
        }
    }
}
int main() {
    int T = Read();
    while(T--) Solve();
}