Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.
Vitya quickly understood all tasks of the teacher, but can you do the same?
You are given an array consisting of n non-negative integers, and m queries. Each query is characterized by one number x and consists of the following consecutive steps:
- Perform the bitwise addition operation modulo 2 (xor) of each array element with the number x.
- Find mex of the resulting array.
Note that after each query the array changes.
First line contains two integer numbers n and m (1 ≤ n, m ≤ 3·105) — number of elements in array and number of queries.
Next line contains n integer numbers ai (0 ≤ ai ≤ 3·105) — elements of then array.
Each of next m lines contains query — one integer number x (0 ≤ x ≤ 3·105).
For each query print the answer on a separate line.
2 2 1 3 1 3
1 0
4 3 0 1 5 6 1 2 4
2 0 0
5 4 0 1 5 6 7 1 1 4 5
2 2 0 2
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1 << 19;
int ch[maxn * 2][2], tot, cnt[maxn];
void insert(int x){
int k = 0, y;
for(int i = 22; i >= 0; --i){
y = (x >> i) & 1;
if(ch[k][y] == 0){
ch[k][y] = ++tot;
}
k = ch[k][y];
}
}
int query(int x){
int k = 0, y, ans = 0;
for(int i = 22; i >= 0; --i){
y = (x >> i) & 1;
if(y == 0){
if(ch[k][0] == 0){
y = 1;
ans |= 1 << i;
}
}
else{
if(ch[k][1] == 0){
y = 0;
ans |= 1 << i;
}
}
k = ch[k][y];
}
return ans;
}
int main(){
int n, m, x;
scanf("%d %d", &n, &m);
memset(cnt, 0, sizeof(cnt));
memset(ch, 0, sizeof(ch));
tot = 0;
for(int i = 1; i <= n; ++i){
scanf("%d", &x);
cnt[x] = 1;
}
for(int i = 0; i < maxn; ++i){
if(cnt[i] == 0){
insert(i);
}
}
int lazy = 0;
for(int i = 1; i <= m; ++i){
scanf("%d", &x);
lazy ^= x;
printf("%d\n", query(lazy));
}
}
/*
题意:定义mex是一个序列中最小未出现的非负整数。对于一个长度为
3e5的序列,一共3e5次操作,每次给定一个数x,让序列中所有数异或x,
然后求新序列的mex。
思路:对原数列中未出现的数按数位从高到低建Trie,在Trie上找最小的
数是很方便的。对于异或操作,实际上就是对这棵Trie上的所有点的值
进行异或,0为1,1为0。但是这样复杂度太高,实际上我们不需要对整棵树
做异或操作,我们用一个变量维护这个值,遍历Trie时,如果该值的某位是1,
说明结点在此处进行了异或操作,每次操作我们对该变量进行异或即可。
那么我们在用Trie求mex时,如果某个结点所在位的下一位没有进行异或操作,
我们就优先访问0结点,进行了异或操作我们就优先访问1结点。
注意:在建树的时候,未出现的数的上限要大一点,不然可能会出现某结点
应该有1结点而未建的情况,导致答案错误。
*/