题意:定义两种作用于二进制数 x x x的事件, A A A事件: x x x变为 ∼ x \sim x ∼x(按位取反), B B B事件: x x x变为 x + 1 x+1 x+1。给一个长为 n ( 1 ≤ n ≤ 2 × 1 0 5 ) n(1\leq n\leq 2\times 10^5) n(1≤n≤2×105)的事件数组,用只包含 A B AB AB的字符串表示。接下来有 q ( 1 ≤ q ≤ 2 × 1 0 5 ) q(1\leq q\leq 2\times 10^5) q(1≤q≤2×105)次询问,每次询问给出一个区间 [ l , r ] ( 1 ≤ l ≤ r ≤ n ) [l,r](1\leq l\leq r\leq n) [l,r](1≤l≤r≤n)和二进制数 x ( 1 ≤ l e n ( x ) ≤ 50 ) x(1\leq len(x)\leq 50) x(1≤len(x)≤50),输出 x x x经过 [ l , r ] [l,r] [l,r]事件后变成的二进制数,强制在线 [ l , r ] [l,r] [l,r]是用 l a s t _ a n s last\_ans last_ans加密的。
题解:
l e n ( x ) ≤ 50 len(x)\leq 50 len(x)≤50,不难想到可以用 64 64 64位整数来存 x x x。既需要位运算 ∼ x \sim x ∼x,又需要四则运算 x + 1 x+1 x+1,不方便进行可合并的线性变换,可以考虑把它们都转化为位运算,或者都转化为四则运算。取反这个位运算不难让人联想到 − x = ∼ x + 1 -x=\sim x + 1 −x=∼x+1的等式(补码性质),所以 ∼ x = − x − 1 \sim x=-x-1 ∼x=−x−1
转化后,可以考虑线段树维护区间线性变化,即区间 [ l , r ] [l,r] [l,r]的事件会令 x x x变为 f x + a fx+a fx+a, A A A事件 f = − 1 , a = − 1 f=-1,a=-1 f=−1,a=−1, B B B事件 f = 1 , a = 1 f=1,a=1 f=1,a=1。
线段树pushup时,设当前节点为 p p p,左儿子为 l s ls ls,右儿子为 r s rs rs, p p p节点的线性变化相当于先进行做儿子的线性变化,再进行右儿子的线性变化,即 x = r s . f × ( l s . f × x + l s . a ) + r s . a = ( l s . f × r s . f ) × x + ( r s . f × l s . a + r s . a ) x=rs.f\times (ls.f\times x+ls.a)+rs.a=(ls.f\times rs.f) \times x+(rs.f\times ls.a+rs.a) x=rs.f×(ls.f×x+ls.a)+rs.a=(ls.f×rs.f)×x+(rs.f×ls.a+rs.a),是一个简单的区间多信息合并,可以关注一下我的写法,我认为比较简洁。
需要注意一个细节,按我的做法,先把 x x x解释成 64 64 64位整数,算出来的 a n s ans ans是也是 64 64 64为整数,若 a n s ans ans为负,则 a n s ans ans的二进制第 l e n ( x ) len(x) len(x)位到第 63 63 63位是 1 1 1,但根据题意,我们要把 x x x重新解释成 l e n ( x ) len(x) len(x)位无符号整数。
时间复杂度为 O ( n log n + q log n ) O(n\log n+q\log n) O(nlogn+qlogn),空间复杂度为 O ( n ) O(n) O(n)
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 2e5 + 5;
int n, q;
string s;
struct sgt {
int l, r;
int f, a; // x -> f * x + a
} t[N << 2];
#define ls (p << 1)
#define rs (p << 1 | 1)
sgt pushup(const sgt &sl, const sgt &sr) {
return {sl.l, sr.r, sl.f * sr.f, sl.a * sr.f + sr.a};
}
void build(int p, int l, int r) {
if (l == r) {
t[p].l = l;
t[p].r = r;
if (s[l] == 'A') {
t[p].f = -1;
t[p].a = -1;
}
else {
t[p].f = 1;
t[p].a = 1;
}
return;
}
int mid = l + r >> 1;
build(ls, l, mid);
build(rs, mid + 1, r);
t[p] = pushup(t[ls], t[rs]);
}
sgt qry(int p, int l, int r) {
if (l <= t[p].l && t[p].r <= r) return t[p];
int mid = t[p].l + t[p].r >> 1;
if (r <= mid)return qry(ls, l, r);
if (l > mid)return qry(rs, l, r);
return pushup(qry(ls, l, r), qry(rs, l, r));
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> q >> s;
s = " " + s;
build(1, 1, n);
ll lastans = 0;
while (q--) {
int tl, tr;
string strx;
cin >> tl >> tr >> strx;
ll x = stoll(strx, nullptr, 2); // string to long long
int l = (tl ^ lastans) % n + 1;
int r = (tr ^ lastans) % n + 1;
if (l > r) swap(l, r);
sgt c = qry(1, l, r);
lastans = x * c.f + c.a & (1ll << strx.size()) - 1; // 保留低len位
for (int i = strx.size() - 1; i >= 0; --i) cout << (lastans >> i & 1);
cout << "\n";
}
}