传送门:点击打开链接
平衡树
Time Limit: 4000/2000MS (Java/Others)
Memory Limit: 128000/64000KB (Java/Others)
Problem Description
神奇的cxlove有一颗平衡树,其树之神奇无法用语言来描述 OrzOrz。 这棵树支持3种操作: 1、加入一个数到树中,维护平衡树的合法性; 2、给一个数X,用O(1)的时间求出来树中的数Y使得 Y ^ X 最大(异或操作, Pascal 写作 xor , 0 ^ 0 = 0 , 1 ^ 1 = 0 , 0 ^ 1 = 1 , 1 ^ 0 = 1 , 2 ^ 3 = 1) 3、给一个数X,用O(1)的时间求出来树中的数Y使得 Y ^ X 最小(异或操作, Pascal 写作 xor , 0 ^ 0 = 0 , 1 ^ 1 = 0 , 0 ^ 1 = 1 , 1 ^ 0 = 1 , 2 ^ 3 = 1) 请你帮忙实现这颗树。 cxlove由于过于牛,有些事情是无法做到的,你能在1s以内通过就好了。 最后补充一句,cxlove是世界冠军!
Input
第一行是数据组数T (T ≤ 100)。
对于每组数据,第一行是操作数N (N ≤ 10000)。
以下 N 行,每行一个字符串一个数字,分别代表:
- insert X ,加入数 X
- qmax X ,求第2种操作的答案
- qmin X ,求第3种操作的答案
输入保证不存在空树Query的情况 (1 ≤ X ≤ 1e9)
Output
对于操作 2 , 3 输出相应的答案。
Sample Input
1 4 insert 1 insert 2 qmin 1 qmax 1
Sample Output
0 3
Hint
Huge input and output. Please do not use: 1. cin ans cout of C++ 2. scanner of Java(Maybe BufferedReader is quicker)
Source
buaads
思路:按位建立字典树。从高位开始。
查询的时候,如果查询最大值,就尝试往和查询的这一位相反的方向走,查询最小值就尝试往和这位相同的方向走。
代码:
#include<cstdio>
#include<cstring>
int ch[1000005][2];
int cnt;
void insert(int x)
{
int root = 1;
for (int i = 30; i >= 0; i--)
{
bool tmp = 0;
if (x & (1 << i)) tmp = 1;
if (!ch[root][tmp]) ch[root][tmp] = ++cnt;
root = ch[root][tmp];
}
}
int quemax(int x)
{
int root = 1, res = 0;
for (int i = 30; i >= 0; i--)
{
bool tmp = 0;
if (x & (1 << i)) tmp = 1;
if (ch[root][!tmp])
{
root = ch[root][!tmp];
res |= 1 << i;
}
else root = ch[root][tmp];
}
return res;
}
int quemin(int x)
{
int root = 1, res = 0;
for (int i = 30; i >= 0; i--)
{
bool tmp = 0;
if (x & (1 << i)) tmp = 1;
if (ch[root][tmp])
{
root = ch[root][tmp];
}
else
{
res |= 1 << i;
root = ch[root][!tmp];
}
}
return res;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
memset(ch, 0, sizeof(ch));
cnt = 1;
int n;
scanf("%d", &n);
while (n--)
{
char s[10];
int x;
scanf("%s %d", s, &x);
if (s[0] == 'i') insert(x);
else if (s[2] == 'a') printf("%d\n", quemax(x));
else printf("%d\n", quemin(x));
}
}
return 0;
}