题目链接:https://vjudge.net/problem/HYSBZ-3261#author=upc_201713
有M个操作,有以下两种操作类型:
1、A x:添加操作,表示在序列末尾添加一个数x,序列的长度N+1。
2、Q l r x:询问操作,你需要找到一个位置p,满足l<=p<=r,使得:
a[p] xor a[p+1] xor ... xor a[N] xor x 最大,输出最大是多少。
题解:设sum为全部数字异或和,后缀^x即为 sum^x^前缀,所以维护一个前缀异或和,建立可持久化字典树,直接查询即可,要注意的是,对于查询的[l, r] 对应的前缀区间应该为[l - 1, r - 1],所以要先预处理一个0。
#include <bits/stdc++.h>
using namespace std;
const int N = 600010;
struct node {
int nex[2];
int sum;
}tree[N * 33];
int n, m, a[N];
int tot;
int root[N];
int newnode() {
tot++;
tree[tot].nex[0] = tree[tot].nex[1] = 0;
tree[tot].sum = 0;
return tot;
}
int update(int pre, int x) {
int now , op;
int cur = newnode();
now = cur;
tree[now] = tree[pre];
tree[now].sum++;
for(int i = 30; i >= 0; i--) {
op = ((x >> i) & 1);
pre = tree[pre].nex[op];
tree[now].nex[op] = newnode();
now = tree[now].nex[op];
tree[now] = tree[pre];
tree[now].sum++;
}
return cur;
}
int query(int pl, int pr, int x) {
int p = 0, op;
int res = 0;
for(int i = 30; i >= 0; i--) {
op = ((x >> i) & 1);
if(tree[tree[pr].nex[op ^ 1]].sum - tree[tree[pl].nex[op ^ 1]].sum) {
res += (1 << i);
pr = tree[pr].nex[op ^ 1];
pl = tree[pl].nex[op ^ 1];
} else {
pr = tree[pr].nex[op];
pl = tree[pl].nex[op];
}
}
return res;
}
int main() {
char op[2];
int l, r, x;
scanf("%d %d", &n, &m);
n++;
root[1] = update(root[0], 0);
for(int i = 2; i <= n; i++) {
scanf("%d", &x);
a[i] = a[i - 1] ^ x;
root[i] = update(root[i - 1], a[i]);
}
while(m--) {
scanf("%s", op);
if(op[0] == 'A') {
scanf("%d", &x);
n++;
a[n] = a[n - 1] ^ x;
root[n] = update(root[n - 1], a[n]);
} else {
scanf("%d %d %d", &l, &r, &x);
printf("%d\n", query(root[l - 1], root[r], a[n] ^ x));
}
}
return 0;
}