题解:P11725 [JOIG 2025] 修学旅行 / School Trip
XiaoHongChong · · 题解
前置知识
- 线段树(不会的可以做一下模板题)。
正文
这里的操作可以理解成:
把字符串的每三个字符分为一组,再按照每组的A和B的数量决定是哪个字符,每次操作长度缩小3 倍。
众所周知,线段树只有两个节点,但是我们可以把它变成3 个节点。
首先,需要观察节点的编号:
1
2 3 4
5 6 7 8 9 10 11 12 13
可以发现,节点
区间的左右断点可以自己算,这里直接给出答案:
令
左区间:
中区间:
右区间:
然后就可以开始写代码了。
代码
注意数组大小,不要开小了!
//f数组为1表示这个字符是A, 为0表示是B
#include <iostream>
using namespace std;
const int MAX = 8e5 + 5;
int n = 1, nn, q, x, maxx, len;
bool f[MAX];
char a[600000];
void build(int u, int l, int r)
{
if (l == r)
{
f[u] = (a[l] == 'A');
maxx = max(maxx, u);
return ;
}
int mid = (r - l + 1) / 3;
build(u * 3 - 1, l, l + mid - 1);
build(u * 3, l + mid, l + mid * 2 - 1);
build(u * 3 + 1, l + mid * 2, r);
f[u] = (f[u * 3 - 1] + f[u * 3] + f[u * 3 + 1] >= 2);
}
void update(int u, int l, int r, int x)
{
if (l == r)
{
f[u] = 1 - f[u];
return ;
}
int mid = (r - l + 1) / 3;
if (x <= l + mid - 1)
update(u * 3 - 1, l, l + mid - 1, x);
else if (l + mid * 2 <= x)
update(u * 3 + 1, l + mid * 2, r, x);
else
update(u * 3, l + mid, l + mid * 2 - 1, x);
f[u] = (f[u * 3 - 1] + f[u * 3] + f[u * 3 + 1] >= 2);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> nn >> q;
for (int i = 1; i <= nn; i++)
n *= 3;
for (int i = 1; i <= n; i++)
cin >> a[i];
build(1, 1, n);
while (q--)
{
cin >> x;
update(1, 1, n, x);
cout << (f[1] ? 'A' : 'B') << endl;
}
return 0;
}