也是很有趣的题目。
观察结论,注意到,在单种颜色超过一半的情况下,答案一定形如 1111... 之类的。
剩下的情况只有 0 和 1(注意到 2 肯定被优先消除)。
于是题目就很简单了,判定 0 和 1 可以通过判定当前是否所有 0 都将被迫消除。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3e5 + 7, md = 1e9 + 7, inf = 1e18;
int n, ret[N], isz;
char a[N];
int ta1[N], ta2[N];
void add(int u, int x, int ta[])
{
for (; u < N; u += u & -u)
ta[u] += x;
}
int query(int u, int ta[])
{
int ret = 0;
for (; u; u &= u - 1)
ret += ta[u];
return ret;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(), cout.tie();
cin >> n >> (a + 1);
int cnt1 = 0, cnt2 = 0;
for (int i = n; i >= 1; i--)
{
cnt1 += (a[i] == '1') ? 1 : -1;
cnt2 += (a[i] == '2') ? 1 : -1;
if (cnt1 > 0)
{
ret[1] += 1;
ret[cnt1 + 1] -= 1;
}
else if (cnt2 > 0)
{
ret[1] += 2;
ret[cnt2 + 1] -= 2;
}
else if ((n - i + 1) & 1)
{
if (a[i] == '0')
add(cnt1 + n + 1, 1, ta1), add(cnt2 + n + 1, 1, ta2), ++isz;
else if (query(cnt1 + n, ta1) + query(cnt2 + n, ta2) == isz) // 被迫删 0
++ret[1], --ret[2];
}
}
for (int i = 1; i < N; i++)
ret[i] += ret[i - 1];
int lst = 1;
for (int i = 1; i < N; i++)
{
ret[i + 1] += ret[i] / 10;
ret[i] %= 10;
}
for (int i = N - 1; i >= 1; i--)
if (ret[i])
{
lst = i;
break;
}
for (int j = lst; j; j--)
cout << ret[j];
return 0;
}
/*
无非就几种:超过一半特判/0/1
*/