Author has gone out of the stories about Vasiliy, so here is just a formal task description.
You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries:
- "+ x" — add integer x to multiset A.
- "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query.
- "? x" — you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.
Multiset is a set, where equal elements are allowed.
Input
The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform.
Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type.
Note, that the integer 0 will always be present in the set A.
Output
For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.
Example
input
10 + 8 + 9 + 11 + 6 + 1 ? 3 - 8 ? 3 ? 8 ? 11
output
11 10 14 13
题意: 有三种操作,+操作表示向集合中插入数字,-操作表示在集合中删除数字,?操作表示询问给出数字与集合中数字最大异或值。集合是多重集合且0一直存在于集合中。
分析: 比较容易想到可以用cnt数组记录节点被几个数字经过,+操作时经过的每个节点cnt++,-操作时经过的每个节点cnt--,?操作时类似求最大异或对解法,不过只能经过cnt>0的节点。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
//注意是多重集合
//0一直都存在于集合中
int son[3300005][2], idx, cnt[3300005];//cnt[i]标记编号为i的节点被经过多少次
void insert(int x, int op)
{
int now = 0;
for(int i = 30; i >= 0; i--)
{
int t = (x>>i)&1;
if(!op)
{
if(!son[now][t])
son[now][t] = ++idx;
now = son[now][t];
cnt[now]++;
}
if(op)
{
now = son[now][t];
cnt[now]--;
}
}
}
int query(int x)
{
int now = 0, num = 0;
for(int i = 30; i >= 0; i--)
{
int t = (x>>i)&1;
if(!cnt[son[now][!t]])//如果最优解不能走
{
now = son[now][t];
num = num|(t<<i);
}
else
{
now = son[now][!t];
num = num|((!t)<<i);
}
}
return num^x;
}
signed main()
{
int n;
cin >> n;
char op[5];
int t;
insert(0, 0);//先把0加入到集合中
while(n--)
{
scanf("%s%d", op, &t);
if(*op == '+')
insert(t, 0);
else if(*op == '-')
insert(t, 1);
else
printf("%d\n", query(t));
}
return 0;
}