[JOIG 2025] 修学旅行 / School Trip 题解

· · 题解

     B
  A  B  B
ABA BBA ABB

拿一个样例,把它的合成过程画个图,发现它是一个满三叉树。再模拟一下它的修改,发现修改这个叶子只会影响它的祖先,这很像线段树的单点修改。

于是我们现场发明一个三叉线段树,单点修改,区间查询,然后就做完了。

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n,q;
int t[5000006];
int a[600005];
void pushup (int pos) {
    int sum = t[3 * pos - 1] + t[3 * pos] + t[3 * pos + 1];
    if (sum >= 2) {
        t[pos] = 1;
    } else {
        t[pos] = 0;
    }
    return;
}
void build (int l,int r,int pos) {
    if (l == r) {
        t[pos] = a[l];
        return;
    }
    int m1 = l + (r - l + 1) / 3,m2 = l + (r - l + 1) * 2 / 3;
    build(l,m1 - 1,3 * pos - 1);
    build(m1,m2 - 1,3 * pos);
    build(m2,r,3 * pos + 1);
    pushup(pos);
    return;
}
void update (int l,int r,int pos,int q) {
    if (l == r) {
        t[pos] ^= 1;
        return;
    }
    int m1 = l + (r - l + 1) / 3,m2 = l + (r - l + 1) / 3 * 2;
    if (l <= q && q < m1) {
        update(l,m1 - 1,3 * pos - 1,q);
    } else if (m1 <= q && q < m2) {
        update(m1,m2 - 1,3 * pos,q);
    } else {
        update(m2,r,3 * pos + 1,q);
    }
    pushup(pos);
    return;
}
signed main () {
    cin >> n >> q;
    int N = pow(3,n);
    for (int i = 1;i <= N;i++) {
        char c;
        cin >> c;
        a[i] = c - 'A';
    }
    build(1,N,1);
    while (q--) {
        int x;
        cin >> x;
        update(1,N,1,x);
        cout << (char)('A' + t[1]) << endl;
    }
    return 0;
}