参考http://blog.csdn.net/lxy767087094/article/details/77719670
题目:http://codeforces.com/contest/842/problem/D
传送门:Codeforces 842D
D. Vitya and Strange Lesson
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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.
Input
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).
Output
For each query print the answer on a separate line.
Examples
input
2 2
1 3
1
3
output
1
0
input
4 3
0 1 5 6
1
2
4
output
2
0
0
input
5 4
0 1 5 6 7
1
1
4
5
output
2
2
0
2
题意:给出一个长度为n的序列和m次操作,每次操作将序列中所有数异或上给定的数x,然后求序列的mex。
mex:给定序列中未出现的最小的非负数。
思路:首先不要被题目中说的每次序列都会变化迷惑,因为异或满足结合律,因此我们只要把所有的x异或起来,就相当于对原序列和一个x求题目中的要求,假设原序列为a[i],和x异或以后得到b[i],我们要求mex(b[i]),就是要在a序列中找一个没出现过且二进制每一位都尽量和x相等的数(先保证最高位相等,然后,以此类推),这一点结合异或和mex的性质可以得出,由于a[i]和x都不超过3e5,因此我们可以建立一个完全二叉树来表下一位示每一个数的出现情况,这颗二叉树其实就是一个二进制树,每一层对应一个数字的二进制中的一位,左子树代表0,右子树代表1,(类似于字典树,不过是只有01两个字符),然后维护每一个结点对应的子树中出现的数的个数,询问的时候就按照上面的红字分析,我们要找的数首先要尽量和x相等,因此我们要按照x的二进制位走,其次要没出现过,因此当我们碰到某个子树中的数全部出现时,我们就必须换另一颗子树走(换子树走的时候就会对答案产生该层对应二进制位权值的贡献)
(未理解透。。。)
别人的代码
#include<bits/stdc++.h>
#define maxn 4001000
#define lc (ch[o][0])
#define rc (ch[o][1])
using namespace std;
bool rev[maxn];
int cnt[maxn];
int ch[maxn][2];
int rt,tot;
int build(int dep)
{
int now=tot++;
if(dep>=0)
{
ch[now][0]=build(dep-1);
ch[now][1]=build(dep-1);
}
return now;
}
void up(int o)
{
cnt[o]=min(cnt[lc],cnt[rc]);
}
void insert(int o,int dep,int x)
{
if(dep==-1)
{
cnt[o]++;
return;
}
int t=(x>>dep&1);
insert(ch[o][t],dep-1,x);
up(o);
}
void query()
{
int ans=0;
int now=rt;
for(int i=19;i>=0;--i)
{
if(rev[i])
{
if(cnt[ch[now][1]]==0)
{
now=ch[now][1];
}
else
{
now=ch[now][0];
ans+=(1<<i);
}
}
else
{
if(cnt[ch[now][0]]==0)
{
now=ch[now][0];
}
else
{
now=ch[now][1];
ans+=(1<<i);
}
}
}
printf("%d\n",ans);
}
int n,m;
int main()
{
rt=build(19);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
{
int x;
scanf("%d",&x);
insert(rt,19,x);
}
while(m--)
{
int x;
scanf("%d",&x);
for(int i=19;i>=0;--i)
{
if(x>>i&1)
{
rev[i]^=1;
}
}
query();
}
return 0;
}